Python Dictionaries

This is a detailed tutorial on Python Dictionary. Learn to store key-value pair data and perform different operations on it using Dictionary data type.

Dictionary is one of the python datatypes that are used to store a number of elements. Dictionary contains elements that have key and value pairs. Therefore, a dictionary collection of elements that are changeable and indexed using keys referring to different values. As keys are used here so, it is an indexed collection and unordered. The elements of a dictionary are also known as items.

It is similar to Associative arrays that are used in most of the other programming languages for the same purpose of storing key-value pair-type data. Python Dictionaries are written between curly braces.

Example. In the following code snippet, a dictionary is created and then printed.

#Creating a Python Dictionary
bio = {
    "name" : "Gurmeet Singh",
    "age" : 21,
    "gender" : "MALE",
    "city": "Ludhiana"
}
#Printing Dictionary
print(bio)

Python Dictionary Example

Fetching Dictionary Items

You can fetch any dictionary item or element using its key index. Python offers two different ways to fetch individual dictionary items. One is the traditional way of using the key names in square brackets, this is exactly how we fetch elements of arrays in other programming languages.

Another way is to use the Python Dictionary get() method. Inside the get method, we’ve to provide the key name as a string parameter.

The use of both of these methods is demonstrated below with the help of an example.

bio = {
    "name" : "Gurmeet Singh",
    "age" : 21,
    "gender" : "MALE",
    "city": "Ludhiana"
}
#Fetching value of the key name using square brackets
print(bio["name"])
#Accessing the value of the key city using Python Dictionary get() method
print(bio.get("city"))

Python Fetching Or Accessing Dictionary Items Example

Adding & Changing Values

You can easily add new items to existing python dictionaries or you can also change the value for any existing item key. To add as well as change the values you just have to use the square brackets notation to specify the key for which you want to add or change the value and then have to assign the value using the  = assignment operator.

In the following example, we’re adding two new key-value pairs to an existing dictionary named bio and then we’re changing the value of one of the keys named score.

bio = {
    "name" : "Gurmeet Singh",
    "age" : 21,
    "gender" : "MALE",
    "city": "Ludhiana"
}
#Adding New Items
bio["country"] = "India"
bio["score"] = "99"

#Changing Item Values
bio["score"] = "100"

print(bio)

Python Dictionary Changing And Adding Values Example

Iterating a Dictionary

You can easily loop through a dictionary using different Python For Loops. Using a simple for loop, the iteration variable will only give you the item keys but you can apply methods on it, to fetch the values as well. The different examples that are given below make use of the for loop in different ways to fetch the dictionary keys, values, and both of them.

Printing Dictionary Keys

The following example shows how you can fetch all of the keys present in a dictionary using the for a loop.

bio = {
    "name" : "Gurmeet Singh",
    "age" : 21,
    "gender" : "MALE",
    "city": "Ludhiana"
}

for info in bio:
    print(info)

Python Loop Through Dictionary Example

Printing Dictionary Values

You can use the square brackets notation to fetch the values of the different keys present in a dictionary while using the simple for loop. This is illustrated in the following example.

bio = {
    "name" : "Gurmeet Singh",
    "age" : 21,
    "gender" : "MALE",
    "city": "Ludhiana"
}

for key in bio:
    print(bio[key])

Python Fetch Dictionary Values Using For Loop Example

values() Function

Python Dictionary also has a values() method that can be used just to fetch the values and not the keys. You can also use this method in the iteration. The example that is given below illustrates the same.

bio = {
    "name" : "Gurmeet Singh",
    "age" : 21,
    "gender" : "MALE",
    "city": "Ludhiana"
}

print(bio.values())

for value in bio.values():
    print(value)

Python Fetching & Iterating Dictionary Values

Fetch key and values both in iteration

You can also fetch the key and values both at the same time using a single for loop without the need for square brackets assessment of the dictionary. Here helps another dictionary method and that is items(). An example showing how you can do this is given below.

bio = {
    "name" : "Gurmeet Singh",
    "age" : 21,
    "gender" : "MALE",
    "city": "Ludhiana"
}

print(bio.items())

for key, value in bio.items():
    print(key + " : " + str(value))

Python Fetch Dictionary Key Values Using Items() Method

Check Key Existence

You can easily check if a key exists in a dictionary or not using the If-else Statement. You can use the membership operators in or not in here to check the condition in the if-else statement. An example showing it is given below.

bio = {
    "name" : "Gurmeet Singh",
    "age" : 21,
    "gender" : "MALE",
    "city": "Ludhiana"
}

if "age" in bio:
    print("The key 'age' is in the dicitonary bio.")
else:
    print("The key 'age ' is not in the dictionary bio.")

Python Dictionary Check If Key Exists Example

Find Dictionary Length

You can easily find out how many elements are there in the dictionary i.e. the length of the dictionary. You’ve just to use the len() method for it and have to pass the dictionary as its parameter. This is similar to finding the size of a python list using this function as it allows us to check the size of any possible python object.

bio = {
    "name" : "Gurmeet Singh",
    "age" : 21,
    "gender" : "MALE",
    "city": "Ludhiana"
}

print(len(bio))

Find Dictionary Length Python Example

Deleting Dictionary items

There are two different methods to delete the items from a Python Dictionary. One is to use the pop() function. It takes the key name as the parameter and it will delete the item having that particular key name.

Another function is the popitem() and it does not take any arguments. The method popitem() in Python Versions earlier than 3.7 deletes any random item from the list. But in Python Version 3.7 or above, this method removes the last element of the dictionary.

An example illustrating the use of both of these functions is given below.

bio = {
    "name" : "Gurmeet Singh",
    "age" : 21,
    "gender" : "MALE",
    "city": "Ludhiana"
}

bio.pop("age")
print(bio)

bio.popitem()
print(bio)

Removing Dictionary Items Python Example

The del keyword can also be used to delete either an item with particular key or the entire dictionary. This is illustrated in the following example. In this example, I’ve used the if-statement and locals() method to check if the dictionary variable exists.

bio = {
    "name" : "Gurmeet Singh",
    "age" : 21,
    "gender" : "MALE",
    "city": "Ludhiana"
}

#Deleting Item with key "city"
del bio["city"]

print(bio)

#Deleting Dictionary
del bio

print(bio)

Deleting Dictionary Items & Dictionary Itself Example

In the above screenshot of the output, you can clearly see that using the del keyword, the dictionary item with a key bio is deleted successfully and the list is printed to the console screen after it. But then we’ve used the del keyword to delete the bio, it deleted the dictionary variable and hence on line 16, it gave an error as that dictionary does not exist.

Empty a Dictionary

You can also make a dictionary item by removing all of the items inside it using a single function named clear(). The following example illustrates the use of clear() function to remove all of the items of the dictionary named bio.

Python Empty A Dictionary Example

The second line of the output shows that the dictionary all the items of dictionary are cleared and now it is empty.

Copying A Dictionary

You can also copy a dictionary to another variable. Again, this can be done in two different ways. One way is to use the Dictionary’s copy() method. Another way is to use the built-in method dict() or you can also call it as dict() constructer. Let’s find how you can use both of these methods to copy dictionaries in the following example.

bio = {
    "name" : "Gurmeet Singh",
    "age" : 21,
    "gender" : "MALE",
    "city": "Ludhiana"
}

print(bio)
print(hex(id(bio)))

#This is NOT COPY, this is referencing another variable to the same dictionary
sameDict = bio
print(sameDict)
print(hex(id(sameDict)))

#This is the first method of copying a Python Dictionary
sameBio = bio.copy()
print(sameBio)
print(hex(id(sameBio)))

#This is the second method of copying a Python Dictionary
sameBio = dict(bio)
print(sameBio)
print(hex(id(sameBio)))

Note. A lot of people have confusion about copying a dictionary and referencing another variable to the same dictionary. This example also intends to clear this confusion. Make sure you read the comments while going through the code.

Python Copy A Dictionary Example

Firstly, I’ve just created another variable sameDict and I’ve assigned the same dictionary named bio to it. Therefore, you can clearly see in the output that in line number 2 and 4 that their memory addresses are the same. Therefore, it is not a copy of the dictionary rather these are just two variables referencing the same dictionary.

The actual two methods of copying a dictionary are illustrated after it and you can clearly see both of the so copied dictionaries have different memory addresses and none of them actually match with the memory address of the original dictionary.

Creating a Dictionary using the dict() Constructor

You can also create a new dictionary using the dict() constructor. Here you need not define the keys using single or double quotes. Also, while defining the key-value pairs using the dict() constructor, you must use the assignment operator = rather than a semi-colon. (;)

bio = dict(name = "Gurmeet Singh", age = 21, gender = "MALE", city = "Ludhiana")
print(bio)
print(type(bio))

Python Dict() Constructor Example

fromkeys() Method – Create a Dictionary with the Same Values for Multiple Keys

You can easily create a dictionary from any python iterable object and can assign the same values to them using the fromkeys() method. The syntax of the function is given below.

dict.fromkeys(keys, value)

It takes two arguments. Only the first argument is needed and the other one is optional. The first argument is basically iterable that contains the keys. The value argument is option and it is basically the same value that has to assigned to the list of keys provided as an iterable in the first argument of this function.

The following examples illustrate the use of fromkeys() method.

keys = ["name","age","gender","city"]

bio = dict.fromkeys(keys)
print(bio)

bio = dict.fromkeys(keys, "HELLO")
print(bio)

Python Dictionary Fromkeys() Function

setdefault() Method – Fetch the key’s value or insert it

The setdefault() method either returns the value of the key if it is present in the dictionary and if it is not present in the list, it first inserts the key-value pair specified in the method as a new item and then returns the value. This method could seem to be a bit tricky for the beginners, but try to understand it with the help of the following example.

bio = { "name" : "Gurmeet Singh", "age" : 21, "gender" : "MALE", "city": "Ludhiana" }

name = bio.setdefault("name", "Gurmeet Singh")
print(name)
print(bio)

name = bio.setdefault("height", "181")
print(name)
print(bio)

Python Dictionary Setdefault() Method

In the above example, when I first applied the setdefault() method with the key name and a value for it. It returns the value that is already in the list. Even if you might have written any other value inside the setdefault’s second parameter, it would have returned the value that already exists in the list for the key provided in the first parameter.

But then again I used the setdefault() method on another key height and with value 181, it returns 181 as this key is not present in the dictionary. So, this function first inserts this key-value pair into the dictionary and then returns the value. The output shown in the above screenshot clearly shows this thing.

Dictionary update() Function

The Dictionary’s update() method is used to either update existing items or to add new items to the dictionary. This function takes an iterable as an argument. The syntax of this function is written below.

dict.update(iterable)

The following example demonstrates its usage. In it, we’ve first updated the value for an existing key name and then we’ve inserted a new item with key height and value 181.

bio = { "name" : "Gurmeet Singh", "age" : 21, "gender" : "MALE", "city": "Ludhiana" }

#Updating Existing Key-Value Pair
bio.update({"name" : "Amandeep Singh"})
print(bio)

#Adding New Item
bio.update({"height" : "181"})
print(bio)

Python Dictionary Update() Method

Python Dictionary Methods

We’ve already published detailed tutorial articles on individual Python Dictionary methods. The links to them are given below. Each of these tutorials contains detailed explanations and different examples to help you understand the different use cases where these methods can be used and how.

clear()

It removes all of the dictionary items.


copy()

This method returns a copy of the dictionary.


fromkeys()

Generates a new dictionary from a given sequence.


get()

It returns the value of a particular key in the dictionary.


items()

Returns a collection object containing tuples of the key, value pair items of the dictionary.


keys()

Returns the dict_keys view object that contains only the list of the dictionary keys.


pop()

Returns and removes the item with a particular key.


popitem()

Returns and removes:

  • a random arbitrary item (Python Version < 3.7)
  • the last inserted item (Python Version >= 3.7)

setdefault()

Returns value for a particular key, if the key exists in the dictionary, and if it does not exist, inserts a new item with that key & returns its value.


update()

Updates a dictionary by adding new items from another dictionary or key, value pairs based iterable.


values()

Returns the dict_values view object that contains only the list of dictionary values.

Leave a Reply

Your email address will not be published. Required fields are marked *