Home » Learn Python » Containers » Python Dictionaries

Python Dictionaries

Python dictionaries are basically lookup tables. They associate a set of keys with corresponding values. In many other programming languages they are known as ‘maps’.

A dictionary is a bit like a set of key-value pairs. As with a set, very efficient to check whether a dictionary contains a particular key. However, unlike a set, in recent versions of Python, dictionaries are ordered. The keys remain in the same order you placed them.

days = {
    'Mon': 'Monday',
    'Tue': 'Tuesday',
}

print(days)

# Add a new key-value pair
days['Wed'] = 'Wednesday'
print(days)

# Check if the dictionary contains
# a particular key
print('Mon' in days)

# Get the value for a particular key
# Throws error if key does not exist.
tue_name = days['Tue']
print(tue_name)

print()

# Get the value for a particular key
# with a default if it doesn't exist.
mon_name = days.get('Mon')
print(mon_name)
pan_name = days.get('Pan')
print(pan_name)
pan_name = days.get('Pan', 'Pancake')
print(pan_name)
{'Mon': 'Monday', 'Tue': 'Tuesday'}
{'Mon': 'Monday', 'Tue': 'Tuesday', 'Wed': 'Wednesday'}
True
Tuesday

Monday
None
Pancake

Iterating Over Dictionaries

To iterate over a dictionary you can fetch the key-value items in the dictionary with the items method, iterating over them with for.

Since each items has both a key and a value, the loop variable is now a tuple containing two variables.

ages = {
    "Bob": 24,
    "Amy": 29,
    "Raj": 35,
}

for (name, age) in ages.items():
    print(f"{name}: {age}")
Bob: 24
Amy: 29
Raj: 35

Iterating Via Keys

Another way to iterate over a dictionary is to fetch the keys, iterate over those, and get the values one by one. This is a bit less efficient if you need all the values.

ages = {
    "Bob": 24,
    "Amy": 29,
    "Raj": 35,
}

for name in ages.keys():
    age = ages[name]
    print(f"{name}: {age}")
Bob: 24
Amy: 29
Raj: 35

Deleting Items

As with list and set, you can remove items from a dictionary using del.

ages = {
    "Bob": 24,
    "Amy": 29,
    "Raj": 35,
}

print(ages)

del ages["Bob"]

print(ages)
{'Bob': 24, 'Amy': 29, 'Raj': 35}
{'Amy': 29, 'Raj': 35}

Leave a Reply

Blog at WordPress.com.

%d