w3resource

Python: Extract single key-value pair of a dictionary in variables

Python Basic: Exercise-137 with Solution

Write a Python program to extract single key-value pair of a dictionary in variables.

Sample Solution-1:

Python Code:

d = {'Red': 'Green'}
(c1, c2), = d.items()
print(c1)
print(c2)

Sample Output:

Red                                                                                                           
Green   

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Sample Solution-2:

Python Code:

dict = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3', 'key4': 'val4'}
print("Extract specific key, value")
x, y = list(dict.items())[0]
print(x, y)
x, y = list(dict.items())[3]
print(x, y)

Sample Output:

Extract specific key, value
key1 val1
key4 val4

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find files and skip directories of a given directory.
Next: Write a Python program to convert true to 1 and false to 0.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]