December 22, 2024

Introduction to Python Dictionaries

In this post and in the accompanying video, we provide a brief and concise introduction to Python dictionaries. The YouTube video accompanying this post is given below.

Dictionaries are data structures used to store data by using key-value pairs. Here is a self-explanatory example of a defining a dictionary

dict1= {"name": "John",
        "age": 25,
        "height": 183,
        "education": "College",
        "random list": [5,6,7]} 

Here we define a dictionary containing basic information about a person. The keys are “name”, “height”, “education”, and “random list”, and the corresponding values are “John”, “25”, “College” and “[5,6,7]”.

Another way of defining a dictionary is explained below

# another way for creating a dictionary 
dictTestScores=dict([('John', 80), ('Adam', 95), ('Jesus', 65)])

That is, we can create a dictionary from a list of pairs containing key-value pairs. To erase the key of the dictionary, we can use the following code line

del dict1['education']
print(dict1)

To erase the last key from the dictionary, we can use the following code line

a1=dict1.popitem()
print(dict1)

Note that the function popitem() returns the key-value pair.

We can use two ways for adding new key-value pairs:

# add a new key-value pair 
dict1['surname']='Doe'
dict1.update({"weigth": 230})
print(dict1)

There are at least two ways for accessing the values stored in keys

#accessing elements 
dict1["name"]
dict1.get("name")

To print the dictionary length, we can use the following code line

print(len(dict1))

To check if a specific key is in the dictionary, we can use the following code lines

'height' in dict1
'education' in dict1

These expressions will return true since both “height” and “education” are the keys that are in the dictionary.

To get all the dictionary keys, we can use the following code line

# get they keys
dict1Keys=dict1.keys()

We can convert the returned keys into a list

# convert it to a list
dict1KeysList=list(dict1Keys)
print(dict1KeysList)

Similarly, we can get the values, and create the list

# get the values
dict1Values=dict1.values()
dict1ValuesList=list(dict1Values)
print(dict1ValuesList)

To loop through keys, values, and key-value pairs stored in the dictionary, we can use the following code lines

# loop through the keys of the dictionary 
for x in dict1:
    print(x)

for x in dict1.keys():
    print(x)

# loop through the values of the dictionary 
for x in dict1.values():
    print(x)

# loop through the keys and values at the same time
for x,y in dict1.items():
    print(x,y)

Finally, to copy the dictionary, we can use the following code line

# copy dictionaries
dict2=dict(dict1)
print(dict2)