Junior — Middle
How can you get all the keys and values from a dictionary in Python?
sobes.tech AI
Answer from AI
In Python, to get all the keys and values from a dictionary, you can use the .items() method. It returns a view of pairs (key, value), which can be iterated over in a loop or converted into a list.
Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
print(f'Key: {key}, Value: {value}')
# Or get separate lists of keys and values
keys = list(my_dict.keys())
values = list(my_dict.values())
print(keys) # ['a', 'b', 'c']
print(values) # [1, 2, 3]