A Guide to Python Dictionaries

by John | July 30, 2023

 

In Python, a dictionary is a built-in data structure used to store collections of key-value pairs. Each key in a dictionary maps to a corresponding value, similar to how words and their definitions are organized in a traditional dictionary. The keys must be unique and immutable objects (e.g., strings, numbers, tuples), while the values can be any type of Python object.

Dictionaries are needed because they provide an efficient way to store and access data using a descriptive label (the key) rather than numerical indices like lists or arrays. This makes dictionaries useful for tasks like mapping names to corresponding information, storing settings and configurations, and organizing data in a structured and easy-to-access manner. With dictionaries, you can quickly look up values based on their associated keys, which makes them a powerful tool for various programming tasks, such as data processing, data storage, and more.

 

 

Dictionary Examples

 

Below we have two example of dictionaries , the first matching names to ages and the second matching letters to their position in the alphabet. In the examples below the names and letters correspond to the dictionary keys and the ages and numbers represent the their associated values.

 

people = {'Harry': 22, 'Paul': 19, 'Sally': 20}

alphabet = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

 

 

We can retrieve the keys from dictionaries in the following way

 



print(people.keys())

print(alphabet.keys())

'''
dict_keys(['Harry', 'Paul', 'Sally'])
dict_keys(['a', 'b', 'c', 'd', 'e'])

'''

 

 

And we can get the values in a similar way

 

print(people.values())

print(alphabet.values())


'''
dict_values([50, 19, 20])
dict_values([1, 2, 3, 4, 5])

'''

 

 

 

Indexing a Dictionary 

 

If we try to index a dictionary value by passing in an index , in the same way as we can do for lists , python will return the following error. 

 

people[0]

 

KeyError: 0

 

Python raises this error due to the fact that dictionaries can't index based off a positional index. Whereas lists can be indexed by an integer value, dictionaries can only access values by passing in the key. 

 

print(people['Harry'])


'''

50
'''


print(alphabet['a'])

'''

1
'''

 

 

 

Dictionary get Method

 

We can extract a value from a dictionary using the get() method , this is a useful method because if the key doesn't exist Python will return either None or a specific value we pass in for this eventuality. Below are a few examples. 

 

people = {'Harry': 22, 'Paul': 19, 'Sally': 20}

p = people.get('Sam')

print(p)

'''

None
'''

 

However we can pass in a default value in the get() method as follows

 

people = {'Harry': 22, 'Paul': 19, 'Sally': 20}

p = people.get('Sam', 'Does not exist')

print(p)

'''

Does not exist
'''

 

If the key does exist this operation will simply return the value associated with that key as shown below. 

 

alphabet = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

print(alphabet.get('a'))

'''
1
'''

 

 

This method is preferable compared to the [ ] retrieval of data in the event that we may not have the key but we don't want Python to raise an exception. 

 

 

 

Adding Items to a Dictionary

 

If we want to add an item to our dictionary we can do so using the following method. 

 

alphabet = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
alphabet['f'] = 6

print(alphabet)


'''
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}

'''

 

We can also use the built in update() method and pass in a key and a value as follows

 

alphabet = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}


alphabet.update({'f': 6})

print(alphabet)


'''

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}

'''

 

 

Clear and Copy Methods

 

The clear() method is a built-in method available for dictionaries in Python. It is used to remove all items (key-value pairs) from the dictionary, effectively making it empty. The method does not return any value; it modifies the dictionary in place.

 

people = {'Harry': 22, 'Paul': 19, 'Sally': 20}

people.clear()

print(people)

'''
{}
'''

 

 

The copy() method is used to create a shallow copy of the dictionary. It returns a new dictionary with the same key-value pairs as the original dictionary. Changes made to the new dictionary will not affect the original dictionary, and vice versa.

 


alphabet = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

original = alphabet.copy()

alphabet['f'] = 6

print(f'orignal = {original}')

print(f'current = {alphabet}')


'''
orignal = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
current = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
'''

 

 

 

 

Dictionary fromkeys Method

 

The fromkeys() method is often used when you want to initialize a new dictionary with a set of keys and assign the same default value to each key. Here's an example to illustrate its usage:

 

Let's say we are programming some sort of game, and we have a list of players from which we want to convert to a dictionary and set the initial score for each player to zero. 

 



players = ['player1', 'player2', 'player3', 'player4', 'player5']

starting_score = 0 

player_dict = dict.fromkeys(players, starting_score)


print(player_dict)

'''

{'player1': 0, 'player2': 0, 'player3': 0, 'player4': 0, 'player5': 0}

'''

 

 

 

Looping through a Python Dictionary

 

Looping through a Python dictionary allows you to iterate over its keys, values, or key-value pairs and perform operations on them. Python provides several methods to accomplish this, such as using for loops, dictionary methods, or list comprehensions. Here's a brief introduction to the common ways of looping through a dictionary:

 

Looping through keys: You can use a for loop to iterate over the keys of the dictionary. The syntax is simple: for key in my_dict:

 

alphabet = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

for key in alphabet.keys():
    print(key)


'''

a
b
c
d
e

'''

 

 

You can loop through the values of a dictionary using the values() method. It returns a view object that you can iterate over. Here we take a more realistic example of when you might want to iterate over a dictionary. Say we wanted to find the average age of the people in our dictionary. We can loop over the values, add them together and then divide through by the len() of our dict. 

 

people = {'Harry': 22, 'Paul': 19, 'Sally': 20}

ages = 0 
for value in people.values():
    ages += value

average_age = ages / len(people)

print(f'average age is {average_age}')


'''
average age is 20.333333333333332

'''

 

 

It is also possible loop through both keys and values simultaneously using the items() method. It returns a view object containing tuples of key-value pairs, again we will try to give a sort of realistic example of when you might want to do this. 

 

Let's say you wanted to loop through the alphabet dictionary we have created and add the values to a new dictionary if the position is an even number. 

 

alphabet = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

new = dict() 


for key, value in alphabet.items():
    if value % 2 == 0:
        new[key] = value



print(new)

'''

{'b': 2, 'd': 4}

'''

 

 

 


Join the discussion

Share this post with your friends!