Close
Close

Python Dictionary


Dictionary is the most important data structure of Python. Like lists and tuples, a dictionary is a collection of items, where each item is in the form of a key-value pair.

Let's take an example to explain it.

Suppose, the cost of a mango is 40
The cost of a banana is 10
The cost of cherry is 20

To store them, we can use a list or a tuple, but using a dictionary is another good way to store all these in a better way.

Like, list is [],

tuple is (),

dictionary is {}.

Let's code using a dictionary.

fruit = {'mango':40, 'banana':10, 'cherry':20}

The above code shows that 'mango' is related to 40, 'banana' to 10 and 'cherry' to 20.

The dictionary fruit has three items - 'mango':40, 'banana':10, 'cherry':20.

In the first item, the key is mango and the value is 40. Similarly, there is a key-value pair in the other two items as well.

dictionary in Python

Creating a Dictionary in Python


As we just saw, the items/elements in a dictionary are enclosed within braces { } and separated by commas.

a = {}
Output

a is an empty dictionary having no item.

fruit = {'mango': 40, 'banana': 10, 'cherry': 20}
print(fruit)
Output
{'mango': 40, 'banana': 10, 'cherry': 20}

fruit is the same dictionary containing three items we saw in the beginning of this chapter. Here, mango, banana and cherry are the keys, and 40, 10 and 20 are values. Therefore, each of the three items contain a key-value pair.

Let's see one more example of a dictionary containing items of different types.

mydict = {'x':[1,2,3,4], 'y':"Hello World", 'z':4.0}
print(mydict)
Output
{'x': [1, 2, 3, 4], 'y': 'Hello World', 'z': 4.0}

There is another way to create dictionaries.

# declaring an empty dictionary
fruit = {}

# adding key-value pairs to dictionary
fruit['mango'] = 40
fruit['banana'] = 10
fruit['cherry'] = 20

print(fruit)
Output
{'mango': 40, 'banana': 10, 'cherry': 20}

In this example, we first declared an empty dictionary fruit. After that, we added all the items one by one. For example, we added an item having 'mango' as key and 40 as value by writing fruit['mango'] = 40.

We can also get all keys and values at one go by using the keys() and values() functions respectively. keys() and values() give us all keys and values of a dictionary respectively. Let's see an example of these functions:

fruit = {'mango':40, 'banana':10, 'cherry':20}
print(list(fruit.keys()))
print(list(fruit.values()))
Output
['mango', 'banana', 'cherry']
[40, 10, 20]

list(fruit.keys()) returned a list of all the keys and list(fruit.values()) returned a list of all the values of the dictionary fruit.

Rules for Creating Python Dictionary


There are some rules which must be followed while creating dictionaries.

Keys must be unique.

A key can’t be present more than once in a dictionary. However, if we give the same key more than once, it will take the value assigned to it in the last element containing the key.

fruit = {'mango':40,'banana':10,'cherry':20, 'mango':60}
print(fruit)
Output
{'mango': 60, 'banana': 10, 'cherry': 20}

In the above example, we gave the key 'mango' twice. So, the key 'mango' took the last assigned value (60).

However, there is no such boundation on values. The same value can be assigned to any number of keys.

fruit = {'mango':40,'banana':20,'cherry':20}
print(fruit)
Output
{'mango': 40, 'banana': 20, 'cherry': 20}

Here, the value 20 is assigned to two keys.

Keys should be some immutable data type.

As already mentioned, data types whose elements can’t be modified, added or deleted are called immutable. int, float, bool, string, tuple are immutable data types. list, dictionary and set are mutable data types.

A key can be an immutable data type only. However, values can be both immutable and mutable data types.

fruit = {'mango':40, 'banana':20, [1, 2]:20}
print(fruit)
Output
Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'

Here, we gave a list as the key of the third element which resulted in an error.

Accessing Elements from Python Dictionary


We use index to extract value from other data types like lists. In a dictionary, we access values by using keys.

There are two ways to extract values using keys in a dictionary - using brackets [ ] or get() function.

In the first method, to access any value of a dictionary, we write name_of_dictionary[key].

fruit = {'mango':40,'banana':10}
print(fruit['mango'])
print(fruit['banana'])
Output
40
10

fruit['mango'] returned the value of the key 'mango' of the dictionary fruit.

In the second method, a value of a dictionary is accessed by writing name_of_dictionary.get(key).

fruit = {'mango':40,'banana':10}
print(fruit.get('mango'))
print(fruit.get('banana'))
Output
40
10

fruit.get('mango') returned the value of the key 'mango' of the dictionary fruit.

In the second method, a value of a dictionary is accessed by writing name_of_dictionary.get(key).

If you try to access a value using a key which doesn’t exist in the dictionary, then accessing with brackets [ ] returns an error whereas accessing with get() simply returns None.

fruit = {'mango':40,'banana':10}
print(fruit.get('cherry'))  # returns None
print(fruit['cherry'])  # throws an error
Output
Traceback (most recent call last):   File "<stdin>", line 3, in <module> KeyError: 'cherry'

Here the key ‘cherry’ is not present in the dictionary fruit. Thus fruit.get(‘cherry’’) returned None and fruit[‘cherry’] gave us an error as stated above.

We can also pass a value in get function. In that case, if the key is not present in the dictionary, that value will be returned instead of None. Let’s look at an example.

fruit = {"mango": 40, "banana": 10}
print(fruit.get("cherry", 50))
Output
50

Since the key 'cherry' is not present in the dictionary fruit, fruit.get("cherry", 50) returned default value of 50.

Changing Elements of Python Dictionary


Dictionaries are mutable, which means that their elements can be changed. The value of a key present in a dictionary can be changed by assigning the new value.

mydict = {'name': 'John', 'age': 45}
mydict['age'] = 50  # changing value
print(mydict)  # printing changed dictionary
Output
{'name': 'John', 'age': 50}

The value of the key 'age' is changed by simply assigning the new value to mydict['age'].

Another way to do this is by using the update() function.

mydict = {'name': 'John', 'age': 45}
mydict.update(age = 50)  # changing value
print(mydict)  # printing changed dictionary
Output
{'name': 'John', 'age': 50}

mydict.update(age = 50) changed the value of the key 'age' to 50.

Adding Elements to Python Dictionary


New elements can be added to a dictionary in the same way they are modified.

The first way to add a new element is to assign the value to the key as shown in the following example.

mydict = {'name': 'John', 'age': 45}
mydict['gender'] = 'male'  # adding a new key-value pair
print(mydict)  # printing changed dictionary
Output
{'name': 'John', 'age': 45, 'gender': 'male'}

mydict['gender'] = 'male' appended a new element with 'gender' as key and 'male' as value to the dictionary.

The second way is to append using the update() function.

mydict = {'name': 'John', 'age': 45}
mydict.update(gender = 'male')  # adding a new key-value pair
print(mydict)  # printing changed dictionary
Output
{'name': 'John', 'age': 45, 'gender': 'male'}

Deleting Elements from Python Dictionary


Python del


The del keyword can be used to delete a single element or the entire list.

mydict = {'name': 'John', 'age': 45, 'gender': 'male'}
del mydict['age']  # deleting element with key 'age'
print(mydict)  # printing changed dictionary
Output
{'name': 'John', 'gender': 'male'}

In the above code, the element having the key 'age' is deleted from the dictionary.

del can also be used to delete an entire dictionary.

mydict = {'name': 'John', 'age': 45, 'gender': 'male'}
del mydict  # deleting dictionary
print(mydict)  # printing dictionary after deleting it
Output
Traceback (most recent call last):   File "<stdin>", line 1, in <module> NameError: name 'mydict' is not defined

In the above code, the entire dictionary colors is deleted. Thus, we got an error on printing the dictionary after deleting it.

Python pop()


The pop() function removes an element having the specified key and returns the value of the removed element.

mydict = {'name': 'John', 'age': 45, 'gender': 'male'}
print(mydict.pop('age'))  # removing element with key 'age' and printing its value
print(mydict)  # printing updated dictionary
Output
45
{'name': 'John', 'gender': 'male'}

mydict.pop('age') removed the element having the key 'age' from the dictionary and returned the value of that element. Therefore, on printing the popped value, 45 got printed.

If we don’t pass any key to the pop() function, we will get an error.

mydict = {'name': 'John', 'age': 45, 'gender': 'male'}
print(mydict.pop())
Output
Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: pop expected at least 1 argument, got 0

Python popitem()


The popitem() function removes the last element from a dictionary and returns the (key, value) pair of the removed element.

mydict = {'name': 'John', 'age': 45, 'gender': 'male'}
print(mydict.popitem())  # removing the last element and printing its key-value pair
print(mydict)  # printing updated dictionary
Output
('gender', 'male')
{'name': 'John', 'age': 45}

mydict.popitem() removed the last element from the dictionary and returned its key-value pair ('gender', 'male').

Before Python 3.7, popitem() removed an arbitrary element from a dictionary, instead of removing the last element

Python clear()


The clear() function removes all the elements from a dictionary.

mydict = {'name': 'John', 'age': 45, 'gender': 'male'}
mydict.clear()  # removing all element from dictionary
print(mydict)  # printing updated dictionary
Output
{}

Python Dictionary Operations


Dictionary Membership Test


We can test if a key is present in a list using the membership operators in and not in.

In a dictionary, the membership test is applicable only for keys, not values.
mydict = {1: 1, 2: 8, 3: 27, 4: 64}
print(2 in mydict)
print(5 in mydict)
print(4 not in mydict)
Output
True
False
False

In the above example, 2 and 4 are the keys whereas 5 is not a key in the dictionary.

As already mentioned, the membership test is not applicable for values. Therefore, in the following example, the membership test returned False even when the value is present in the dictionary.

mydict = {1: 1, 2: 8, 3: 27, 4: 64}
print(8 in mydict)  # 8 is not a key
Output
False

Iteration Through a Python Dictionary


The different ways to iterate through a dictionary are discussed below.

Looping Through Keys


We can iterate through the keys of a dictionary using a for loop. Since we can iterate over keys, we can use those keys to get values also. Let’s look at an example.

mydict = {'name': 'John', 'age': 45, 'gender': 'male'}
for k in mydict:
   print("key =", k)
    print("value =", mydict[k])
Output
key = name
value = John
key = age
value = 45
key = gender
value = male

A variable k goes to each element in the dictionary mydict and takes its key. Therefore, in the first iteration, k is 'name', in the second iteration it is 'age' and so on.

Looping Through Values


We can also iterate through the values of a dictionary using the values() function. We can use this function if we want to access just the values.

mydict = {'name': 'John', 'age': 45, 'gender': 'male'}
for v in mydict.values():
    print("value =", v)
Output
value = John
value = 45
value = male

Note that we are iterating through mydict.values() instead of mydict. The variable v goes to each element in the dictionary mydict and takes its value.

Looping Through Keys and Values


We can iterate through both keys and values of a dictionary using the items() function. We can use this function if we want to access just the values.

mydict = {'name': 'John', 'age': 45, 'gender': 'male'}
for k, v in mydict.items():
    print("key =", k)
    print("value =", v)
Output
key = name
value = John
key = age
value = 45
key = gender
value = male

In each iteration, k takes the key and v takes the value.

Different Ways to Create a Python Dictionary


We already know how to create a dictionary.

An empty dictionary is created as follows.

mydict = {}

A dictionary having elements is created as follows.

mydict = {'name': 'John', 'age': 45, 'gender': 'male'}

It can also be created as follows.

mydict = {}

mydict['name'] = 'John'

mydict['age'] = 45

mydict['gender'] = 'male'

Dictionaries can also be created using the dict() function.

An empty dictionary can be created using dict() as shown below.

mydict = {}
print(mydict)
Output
{}

A dictionary having elements can also be created by passing the key-value pairs to dict() as shown in the following example.

mydict = dict(name = 'John', age = 45, gender = 'male')
print(mydict)
Output
{'name': 'John', 'age': 45, 'gender': 'male'}

Python Copying Dictionary


Let’s look at the different ways we can copy a dictionary.

Simple Assignment


A dictionary can be copied to a variable by simply assigning it to the variable.

dict1 = {'a': 20, 'b': 10, 'c': [1, 2, 3]}
dict2 = dict1
print(dict2)
Output
{'a': 20, 'b': 10, 'c': [1, 2, 3]}

Here, the dictionary stored in the variable dict1 is assigned to the variable dict2. This results in both the variables storing the same dictionary. As a result, if some change is made in dict2, it will also get reflected in dict1, which is often undesirable.

Let’s see how a change in dict2 is getting reflected in dict1.

dict1 = {'a': 20, 'b': 10, 'c': [1, 2, 3]}
dict2 = dict1
dict2['b'] = 30
dict2['c'] = [1, 2, 3, 4]
print("Original dictionary:", dict1)
print("New dictionary:", dict2)
Output
Original dictionary: {'a': 20, 'b': 30, 'c': [1, 2, 3, 4]}
New dictionary: {'a': 20, 'b': 30, 'c': [1, 2, 3, 4]}

After assigning dict1 to dict2, the values assigned to the keys 'b' and 'c' are changed. The same changes got reflected in dict1 also. This is because both the variables are pointing to the memory location of the same dictionary.

To prevent this, we can use the copy() function.

Python copy()


copy() is a function in Python which creates a shallow copy of a dictionary.

dict1 = {'a': 20, 'b': 10, 'c': [1, 2, 3]}
dict2 = dict1.copy()
dict2['b'] = 30
dict2['c'] = [1, 2, 3, 4]
print("Original dictionary:", dict1)
print("New dictionary:", dict2)
Output
Original dictionary: {'a': 20, 'b': 10, 'c': [1, 2, 3]}
New dictionary: {'a': 20, 'b': 30, 'c': [1, 2, 3, 4]}

In this example, a shallow copy of dict1 is created using copy() and that copy is assigned to dict2. As a result, modifying dict2 didn’t modify dict1 because now the variables are pointing to the memory addresses of different dictionaries.

Python dict()


A dictionary can also be copied by passing it to the dict() function.

dict1 = {'a': 20, 'b': 10, 'c': [1, 2, 3]}
dict2 = dict(dict1)
dict2['b'] = 30
dict2['c'] = [1, 2, 3, 4]
print("Original dictionary:", dict1)
print("New dictionary:", dict2)
Output
Original dictionary: {'a': 20, 'b': 10, 'c': [1, 2, 3]}
New dictionary: {'a': 20, 'b': 30, 'c': [1, 2, 3, 4]}

We created a new dictionary having all the elements of dict1 using dict(dict1) and assigned this newly created dictionary to dict2.

Built-in Functions in Python for Dictionary


The functions available in Python which can be used with dictionaries are shown below.

len()


It returns the number of elements in a dictionary.

mydict = {'name': 'John', 'age': 45, 'gender': 'male'}
print(len(mydict))
Output
3

sorted()


It returns a list of the keys of a dictionary in sorted order.

mydict = {'name': 'John', 'age': 45, 'gender': 'male'}
print(sorted(mydict))
Output
['age', 'gender', 'name']

Here a sorted list of the keys of the dictionary is returned..

Look at another example in which the keys are numeric.

mydict = {2: 'John', 1: 45, 3: 'male'}
Output
[1, 2, 3]

To sort the keys in descending order, pass another argument reverse=True to the sorted function.

mydict = {2: 'John', 1: 45, 3: 'male'}
print(sorted(mydict, reverse=True))
Output
[3, 2, 1]

any()


It returns True if any of the keys in a dictionary are True. Otherwise, it returns False.

mydict = {1: 1, 'a': 2, True: 3}
print(any(mydict))
Output
True

any(mydict) returned True because all the keys of the dictionary mydict are non-zero or True.

Look at another example where one key of the dictionary is False.

mydict = {1: 1, 'a': 2, False: 3}
print(any(mydict))
Output
True

We have one key of the dictionary False, but still the any() function returned True. This is because if at least one key is non-zero or True, then the function returns True.

Now consider the following example.

mydict = {'': 1, 0: 2, False: 3}
print(any(mydict))
Output
False

The function returned False because the first key is a null string, the second key is 0 and the third key is False.

all()


It returns True if all the keys in a dictionary are True. Otherwise, it returns False.

mydict = {1: 1, 'a': 2, True: 3}
print(all(mydict))
Output
True
mydict = {1: 1, 'a': 2, False: 3}
print(all(mydict))
Output
False

In this example, one key is False and so the all() function returned False.

Other Dictionary Functions in Python


We have already looked at some of the dictionary functions like get(), update(), pop(), popitem(), clear() and copy(). Other useful functions are shown below.

Python keys()


It returns an object which contains the keys of a dictionary in the form of a list.

mydict = {'name': 'John', 'age': 45, 'gender': 'male'}
print(mydict.keys())
Output
dict_keys(['name', 'age', 'gender'])

Python values()


It returns an object which contains the values of a dictionary in the form of a list.

mydict = {'name': 'John', 'age': 45, 'gender': 'male'}
print(mydict.values())
Output
dict_values(['John', 45, 'male'])

items()


It returns an object which contains the key-value pairs of a dictionary in the form of a list.

mydict = {'name': 'John', 'age': 45, 'gender': 'male'}
print(mydict.items())
Output
dict_items([('name', 'John'), ('age', 45), ('gender', 'male')])

fromkeys()


It creates and returns a dictionary with the specified keys and the specified value. Using this function, all the keys are assigned the same value.

mykeys = {'a', 'b', 'c', 'd'}  # defining keys
myvalue = 10  # defining value
mydict = dict.fromkeys(mykeys, myvalue)  # creating dictionary
print(mydict)
Output
{'c': 10, 'd': 10, 'a': 10, 'b': 10}

In this example, a sequence of keys is assigned to the variable mykeys and the value is assigned to the variable myvalue. A dictionary is created with the keys stored in mykeys and the value stored in myvalue assigned to each by writing dict.fromkeys(mykeys, myvalue).

I have no special talent. I am only passionately curious.
- Albert Einstein


Download Our App.
BlogsDope App
Get it on Google Play
Ask Yours
Post Yours
Doubt? Ask question