Dictionaries store data in pairs: keys and values. You often need to get just the keys, just the values, or both together to work with the data.
0
0
Dictionary keys, values, and items in Python
Introduction
When you want to list all the names (keys) in a phone book dictionary.
When you need all the phone numbers (values) from a contacts dictionary.
When you want to see each name and phone number together to print or process them.
When you want to check if a certain key exists in the dictionary.
When you want to loop through all pairs to update or analyze data.
Syntax
Python
dict.keys() dict.values() dict.items()
dict.keys() returns all the keys in the dictionary.
dict.values() returns all the values in the dictionary.
dict.items() returns pairs of (key, value) as tuples.
Examples
This shows all keys: 'apple' and 'banana'.
Python
my_dict = {'apple': 3, 'banana': 5}
keys = my_dict.keys()
print(keys)This shows all values: 3 and 5.
Python
my_dict = {'apple': 3, 'banana': 5}
values = my_dict.values()
print(values)This shows all key-value pairs as tuples.
Python
my_dict = {'apple': 3, 'banana': 5}
items = my_dict.items()
print(items)Sample Program
This program creates a dictionary of fruits with quantities. It prints all keys, values, and key-value pairs.
Python
fruits = {'apple': 10, 'banana': 20, 'cherry': 30}
print('Keys:', list(fruits.keys()))
print('Values:', list(fruits.values()))
print('Items:', list(fruits.items()))OutputSuccess
Important Notes
The keys(), values(), and items() methods return special views, so converting them to a list shows them clearly.
You can loop directly over these views in a for-loop without converting.
Summary
Dictionaries store data as key-value pairs.
Use keys() to get all keys, values() for all values, and items() for all pairs.
These methods help you access and work with dictionary data easily.