Skip to main content

Keys and Values in Dictionaries

In Python dictionaries, each element consists of a key and a corresponding value. These keys and values together form what is known as a key-value pair.

Understanding the roles and characteristics of keys and values is essential for effective use of dictionaries in Python programming.

Uniqueness: Keys in a dictionary must be unique. No two keys can have the same name.

Immutability: Keys must be immutable objects such as strings, numbers, or tuples. This ensures that keys remain constant and can be reliably used for indexing.

Hashability: Since dictionaries use a hash table implementation for efficient lookups, keys must be hashable. Immutable types like strings and numbers are hashable, while mutable types like lists and dictionaries are not.

Keys and Values​

Create a file sampleDict.py

sampleDict.py
# Define a sample dictionary
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

MyDict.py
keys = my_dict.keys()
print("Keys:", keys)
Output
Keys: dict_keys(['name', 'age', 'city'])

Iterating over keys and values​

Iterating over keys and values in a dictionary allows you to access both the keys and their corresponding values one by one. This is often necessary when you need to perform operations on each key-value pair or extract specific information from the dictionary.

MyDict.py
# Iterate over keys and values
print("Iterating over keys and values:")
for key in keys:
print("Key:", key, "Value:", my_dict[key])
Output
Iterating over keys and values:
Key: name Value: John
Key: age Value: 30
Key: city Value: New York