Python: Extract single key-value pair of a dictionary in variables
Extract Dictionary Pair
Write a Python program to extract a single key-value pair from a dictionary into variables.
Sample Solution-1:
Python Code:
# Create a dictionary 'd' with a single key-value pair.
d = {'Red': 'Green'}
# Retrieve the items (key-value pairs) from the dictionary and unpack them into 'c1' and 'c2'.
# Note: Since 'd' contains only one key-value pair, we can safely unpack the items.
(c1, c2), = d.items()
# Print the first element, 'c1', which corresponds to the key 'Red'.
print(c1)
# Print the second element, 'c2', which corresponds to the value 'Green'.
print(c2)
Sample Output:
Red Green
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
Python Code Editor:
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 Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics