Python Dictionaries Tutorial for Beginners
Learn how to use Python dictionaries, all key methods, and key attributes
If you are new to all things python have a look at this resource , python data types because we will be using some of those concepts in this article.
Dictionaries are unordered python data types used to store key, value pairs. The key is separated from the values by a colon and separate keys are separated from each other by a comma.
Python dictionaries behave similarly to your typical English dictionary. Think of the KEY as the word you are searching for and the VALUE as the meaning of the word you are searching for. The only difference is that now, in python, instead of the key being just an English word , it could be a variable name for a name , a value, a client-key or client details etc. and the VALUE is now the actual name, value, client-key or details
NOTE : For this article I used Google-Colab notebooks, but the same code will work on any python IDE. >>
represents the output.
Declaring/Initialising Dictionaries
dict()
constructor is used to initialize dictionaries in python. Alternatively you can the curly brackets { }
. We will begin by creating empty dictionary.
1. my_dict = dict()
2. my_dict = {}
Both 1 and 2 will give the same result i.e. create an empty dictionary. It is however advisable to use 1 since it easier to follow.(We will take a look at how to add data to dictionaries later on)
We can also declare non-empty dictionaries. As stated earlier , dictionaries behave like lists in the sense that they can store multiple data types. The dict()
constructor will help us create dictionaries directly from sequences of key-value pairs. This means the key values pairs should be in a datatype that allows you to store a sequence of values e.g. lists
, tuple
, sets
from_tupple =dict((("student1",99)("student2",83),("student3",70) )) from_list = dict([('student1',99), ('student2',83),('student3',70)]) from_set = dict(set([('student1',99), ('student2',83), ('student3',70)])) # We print out one and confirm whether they are all the same print(from_tuple) >> {'student1': 99, 'student2': 83, 'student3': 70}
On comparing the two, we find they are the same
from_list == from_tuple
>> True
from_tuple == from_set
>> True
The values of each key need not be single values e.g. a number or a word, they can be lists or tuples or a sentence. The keys can also be of multiple data types but they can on only be a string or an integer.
{"Africa":set(['Kenya','Ghana','South Africa']), "Europe":['Britain','Sweden'], "numbers":(1,2,3,4), 0:"Max", 1:"Lewis"} >> {0: 'Max', 1: 'Lewis', 'Africa': {'Ghana', 'Kenya', 'South Africa'}, 'Europe': ['Britain', 'Sweden'], 'numbers': (1, 2, 3, 4)}
Inserting Values
In dictionaries we use the KEYS as references for VALUES we want to insert. We can also insert new KEYS into the dictionary with their values. The format used is <dict_name>[<key>] = <value>
new_dict = dict() new_dict["Africa"]="Kenya" new_dict >> {'Africa': 'Kenya'}
Variables can also be used to insert values into a dictionary
# The room sizes are arbitrary values,
# could be in whichever area metric you prefer
# sq ft. , sq meters etc.room1_size = 97.56
room2_size = 344.22
room3_size = 123.7room_size_dict = dict()
room_size_dict[1] = room1_size
room_size_dict[2] = room2_sizeroom_size_dict
>>{1: 97.56, 2: 344.22, 3: 123.7}
We can also use loops to insert into dictionaries, say in a case where the values are/are to be lists or any other mutable data type for that matter.
# I will use numpy to generate a random list of 30 numbers # You can ignore this for now if it new to you, it is simply for explanation purposes import numpy as np random_numbers = np.random.randint(0,100,30) random_numbers >> array([69, 74, 74, 5, 79, 52, 58, 74, 35, 94, 60, 36, 44, 23, 58, 17, 89,54, 19, 32, 82, 5, 80, 67, 8, 77, 34, 88, 73, 76])
Initializing the dictionary with empty lists
# Intializing with lists # This is okay if you have few keys and already know what they could be my_dict = dict([("big",[]),("medium",[]),("small",[])]) for number in random_numbers: if number < 31: my_dict["small"].append(number) elif number > 70: my_dict["big"].append(number) else: my_dict["medium"].append(number)my_dict >>{'big': [74, 74, 79, 74, 94, 89, 82, 80, 77, 88, 73, 76], 'medium': [69, 52, 58, 35, 60, 36, 44, 58, 54, 32, 67, 34], 'small': [5, 23, 17, 19, 5, 8]}
Doing it dynamically
# This is preferable if you aren't entirely sure of what values you will get. # I am limiting my if cases due for example purposes # You may have the keys generated in another manner that would make them completely random # Here the first for-loop generates my key-value pairs. Yours could be generated by some other function that you choose to use my_new_dict = dict() paired_list = [] for number in random_numbers: if number < 31: my_key = "small" elif number > 70: my_key="big" else: my_key="medium" # Populate the list of key value pairs paired_list.append((my_key, number))
for key, value in paired_list: # Check if the key already exists in the dictionary # If not, add that key if key not in my_new_dict: #assign an empty list to that key my_new_dict[key]=[] my_new_dict[key].append(value) my_new_dict >>{'big': [74, 74, 79, 74, 94, 89, 82, 80, 77, 88, 73, 76], 'medium': [69, 52, 58, 35, 60, 36, 44, 58, 54, 32, 67, 34], 'small': [5, 23, 17, 19, 5, 8]}
Notice the result is the same. The values may different for you depending on what values are generated by np.random
Reading Values
If you had noticed at some point in the INSERTING VALUES section I used if key not in my_new_dict
. What happened here was that we read the key values in the dictionary and checked to see if a certain key was there.
We can read dictionary values using their keys.
# "small" is the key we use to retrieve values from the dictionary my_new_dict["small"] >> [5, 23, 17, 19, 5, 8]
We can also loop through keys and values in a dictionary. When you loop through a dictionary what is retrieved is the only the key.
for i in my_new_dict:
print(i)>> medium
>> big
>> small
You are probably thinking we could adjust the same and get the values too because dictionaries are key value pairs. Let us try that and see what happens.
for i,j in my_new_dict: print(i,j)>> ----------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-32-cb3b76454f12> in <module>() ----> 1 for i,j in my_new_dict: 2 print(i,j)ValueError: too many values to unpack (expected 2)
So, no, we can’t do that.
Introducing dict.keys(), dict.values(), dict.items()
.keys()
returns all keys in the dictionary .values()
returns all the values in the dictionary.
my_new_dict.keys() >> dict_keys(['medium', 'big', 'small']) my_new_dict.values() >> dict_values([[69, 52, 58, 35, 60, 36, 44, 58, 54, 32, 67, 34], [74, 74, 79, 74, 94, 89, 82, 80, 77, 88, 73, 76], [5, 23, 17, 19, 5, 8]])
At this point you might be thinking you could just zip the keys and values and retrieve them that way. That will technically work as shown below.
# AVOID using this for i,j in zip(my_new_dict.keys(), my_new_dict.values()): print(i,j) >> medium [69, 52, 58, 35, 60, 36, 44, 58, 54, 32, 67, 34] >> big [74, 74, 79, 74, 94, 89, 82, 80, 77, 88, 73, 76] >> small [5, 23, 17, 19, 5, 8]
There is a better way to do it and that is by using dict.items()
# Notice it will return a list of tuples containing keys and their values my_new_dict.items() >> dict_items([('medium', [69, 52, 58, 35, 60, 36, 44, 58, 54, 32, 67, 34]), ('big', [74, 74, 79, 74, 94, 89, 82, 80, 77, 88, 73, 76]), ('small', [5, 23, 17, 19, 5, 8])])
Now if we were to loop through the dictionary we would use:
for i,j in my_new_dict.items(): print(i,j) >> medium [69, 52, 58, 35, 60, 36, 44, 58, 54, 32, 67, 34] >> big [74, 74, 79, 74, 94, 89, 82, 80, 77, 88, 73, 76] >> small [5, 23, 17, 19, 5, 8]
.items()
behaves in a manner similar to zip only that now it is a dictionary attribute that zips the keys and values.
Now that you have a better of python dictionary with regards to creation, retrieval and insertion of data, take a look at dictionary operations.
Other Dictionary Operations
First , python has a special type of dict
that remembers/preserves the insertion order.
dict( numbers=(1,2,3,4), k ="Lewis", Europe=['Britain','Sweden'], Africa=set(['Kenya','Ghana','South Africa'])) >> {'Africa': {'Ghana', 'Kenya', 'South Africa'}, 'Europe': ['Britain', 'Sweden'], 'k': 'Lewis', 'numbers': (1, 2, 3, 4)} # Using an OrderedDict from collections import OrderedDict OrderedDict(numbers=(1,2,3,4), k ="Lewis", Europe=['Britain','Sweden'], Africa=set(['Kenya','Ghana','South Africa'])) >> OrderedDict([('numbers', (1, 2, 3, 4)), ('k', 'Lewis'), ('Europe', ['Britain', 'Sweden']), ('Africa', {'Ghana', 'Kenya', 'South Africa'})])
Note how initially the entries were sorted by keys but with the OrderedDict the order of entry was preserved.
dict.clear()
empties/ deletes all items in a dictionary.
my_new_dict >> {'big': [79, 93, 79, 77, 89, 89, 93, 77, 74, 89], 'medium': [47, 54, 44, 66, 34, 43, 66, 56, 51], 'small': [23, 14, 22, 18, 29, 14, 2, 11, 2, 11, 26]} my_new_dict.clear() my_new_dict >> {}
dict.get(<key>,<default>)
returns the values for the specified key
my_new_dict.get("medium") >> [69, 52, 58, 35, 60, 36, 44, 58, 54, 32, 67, 34] # If the key is not found , the default value is returned my_new_dict.get("tall","No such key") >> 'No such key'
dict.pop(<key>)
removes the item at the specified key
d = dict( numbers=(1,2,3,4), k ="Lewis", Europe=['Britain','Sweden'], Africa=set(['Kenya','Ghana','South Africa']))d.pop("k") d >> {'Africa': {'Ghana', 'Kenya', 'South Africa'}, 'Europe': ['Britain', 'Sweden'], 'numbers': (1, 2, 3, 4)}
dict.popitem()
removes the last item in the dictionary
d = dict( numbers=(1,2,3,4), k ="Lewis", Europe=['Britain','Sweden'], Africa=set(['Kenya','Ghana','South Africa'])) d.popitem() d >> {'Europe': ['Britain', 'Sweden'], 'k': 'Lewis', 'numbers': (1, 2, 3, 4)}
— — — — — — — — —
Congratulations !! for getting to the end of the article and I believe you have at least learnt one new thing when it comes to python dictionaries.
Keep on practicing and eventually the concepts come to you a bit easier.
Thank you for you time
Other resources you can have a look at :
THE END