Python Dictionary



A Dictionary is used to store data values in key:value pair.

A Dictionary is an ordered* collection, changeable and does not allow duplicates.

Note: In Python 3.6 and earlier versions, dictionaries are unordered. As of Python version 3.7 and up, dictionaries are ordered.


Creating Python Dictionary

To create a dictionary, you place items inside curly braces {} separated by commas.

In a dictionary, an item has a key, and a corresponding value that is expressed as a pair (key:value).

Keys must be of immutable type (string, number, or tuple with immutable elements) and must be unique. In the other hand, values can be of any data type and can be duplicated.

# empty dictionary
my_dict = {}

# dictionary with integer keys
my_dict = {0: "kiwi", 1: "blueberry", 2:"apple"}

# dictionary with mixed keys
my_dict = {0: "apple", "name": "James" }

You can also create a dictionary using the built-in dict() function.

# using dict() function
my_dict = dict({0: "kiwi", 1: "blueberry", 2:"apple"})

# using dict() by passing a sequence which has in each item a (key, value) pair
my_dict = dict([(1, "apple"), (2, "kiwi")])

Dictionary Items

Dictionary items are ordered, changeable, and do not allow duplicates.

Dictionary items are composed of key:value pairs and can be referenced using the key name.

In the following example, we will print the "name" and the "department" of the dictionary.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

print(my_dict["name"])
print(my_dict["department"])

Output

James 
Marketing

Ordered or Unordered?

Note: Ad of Python version 3.7 and up, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

Dictionaries are ordered, meaning that the items have a defined order, and that order will not change.


Changeable

Dictionaries are changeable or mutable, meaning that we can change, add or remove items after the dictionary has been created.


Duplicates Not Allowed

Dictionaries cannot have two items with the same key.

In the following example, we will duplicate values. The duplicate values will overwrite existing values.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing",
    "department":  "Sales"
}

print(my_dict)

Output

{'name': 'James', 'age': 23, 'department': 'Sales'}

Dictionary Length

You can use the len() function to determine how many items a dictionary has.

In the following example, we will get the number of items in a dictionary.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing",
    "department":  "Sales"
}

print(len(my_dict))

Output

3

Dictionary Items - Data Types

The values in dictionary items can be of any data type.

In the following example, we will use string, int, boolean, and list data types.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Sales",
    "full-time": True,
    "hobbies": ["calligraphy", "photography", "hiking"]
}

print(my_dict)

Output

{'name': 'James', 'age': 23, 'department': 'Sales', 'full-time': True, 'hobbies': ['calligraphy', 'photography', 'hiking']}

type()

In Python, dictionaries are defined as objects with the data type "dict".

In the following example, we will output the type of a dictionary.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

print(type(my_dict))

Output

<class 'dict'>

Access Dictionary Items

There are different ways that you can use to access the items of a dictionary.


Accessing Items

To access the items of a dictionary, you can refer to its key name, inside square brackets [] or using the get() method.

If you use the square brackets [], a KeyError can be raised if the key is not found in the dictionary. On the other hand, the get() method returns None if the key is not found.

In the following example, we will access the "department" key.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

x = my_dict["department"]

print(x)

Output

Marketing

In the following example, we will use the get() method that will give the same result.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

x = my_dict.get("department")

print(x)

Output

Marketing

Get Keys

The keys() method will return a list of all the keys in the dictionary.

In the following example, we will get a list of the keys.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

print(my_dict.keys())

Output

dict_keys(['name', 'age', 'department'])

The list of the keys returned by the keys() method is a view of the dictionary, meaning that any changes that occur in the dictionary will be reflected in the keys list.

In the following example, we will add a new item to the original dictionary and see that the keys list also gets updated.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

x = my_dict.keys()

# before the change
print(x)

my_dict["city"] = "Seattle"

# after the change
print(x)

Output

dict_keys(['name', 'age', 'department']) 
dict_keys(['name', 'age', 'department', 'city'])

Get Values

The values() method will return a list of all the values in the dictionary.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

print(my_dict.values())

Output

dict_values(['James', 23, 'Marketing'])

The list of the values returned by the values() method is a view of the dictionary, meaning that any changes that occur in the dictionary will be reflected in the values list.

In the following example, we will change the value in the original dictionary and see that the values list also gets updated.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

x = my_dict.values()

# before the change
print(x)

my_dict["department"] = "Development"

# after the change
print(x)

Output

dict_values(['James', 23, 'Marketing']) 
dict_values(['James', 23, 'Development'])

In the following example, we will add a new item to the original dictionary and see that the values list also gets updated.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

x = my_dict.values()

# before the change
print(x)

my_dict["city"] = "Seattle"

# after the change
print(x)

Output

dict_values(['James', 23, 'Marketing']) 
dict_values(['James', 23, 'Marketing', 'Seattle'])

Get Items

The ìtems() method will return each item in a dictionary, as tuples in a list.

In the following example, we will get the list of the dictionary key:value pairs.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

print(my_dict.items())

Output

dict_items([('name', 'James'), ('age', 23), ('department', 'Marketing')])

The list of the key:value pairs returned by the items() method is a view of the items of the dictionary, meaning that any changes that occur in the dictionary will be reflected in the items list.

In the following example, we will make a change in the original dictionary and see that the items list also gets updated.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

x = my_dict.items()

# before the change
print(x)

my_dict["department"] = "Development"

# after the change 
print(x)

Output

dict_items([('name', 'James'), ('age', 23), ('department', 'Marketing')]) dict_items([('name', 'James'), ('age', 23), ('department', 'Development')])

In the following example, we will add a new item to the original dictionary and see that that items list also gets updated.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

x = my_dict.items()

# before the change
print(x)

my_dict["city"] = "Seattle"

# after the change
print(x)

Output

dict_items([('name', 'James'), ('age', 23), ('department', 'Marketing')]) 
dict_items([('name', 'James'), ('age', 23), ('department', 'Marketing'), ('city', 'Seattle')])

Check if Key Exists

You can use the in keyword to determine if a specified key is present in a dictionary.

In the following example, we will check if "department" is present in the dictionary.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

if "department" in my_dict:
    print("Yes, 'department' is present as a key in the my_dict dictionary")

Output

Yes, 'department' is present as a key in the my_dict dictionary

Change Dictionary Items

Dictionaries are mutable. So you can change the value of existing dictionary items, and there are two ways to do it.


Change Values

To change the value of a specific item in a dictionary, you can refer to its key name.

In the following example, we will change the "age" to 26.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

my_dict["age"] = 26
print(my_dict)

Output

{'name': 'James', 'age': 26, 'department': 'Marketing'}

Update Dictionary

You can also use the update() method to update the dictionary with the items from the given argument.

The argument passed to the update() method must be a dictionary or an iterable object with key:value pairs.

In the following example, we will update the value of the "department" key in the dictionary using the update() method.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

my_dict.update({"department": "Development"})

print(my_dict)

Output

{'name': 'James', 'age': 23, 'department': 'Development'}

Add Dictionary Items

Dictionaries are mutable. So you can add new items to the dictionary, and there are two ways to do it.


Adding Items

You can add a new item to the dictionary by using a new index key and assigning a value to it.

In the following example, we will add a new item ("city" : ''Seattle") to the dictionary.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

my_dict["city"] = "Seattle"

print(my_dict)

Output

{'name': 'James', 'age': 23, 'department': 'Marketing', 'city': 'Seattle'}

Update Dictionary

You can also use the update() method to update the dictionary with the items from the given argument. If the item does not exist, the item will be added.

The argument passed to the update() method must be a dictionary or an iterable object with key:value pairs.

In the following example, we will add a new item ("city" : ''Seattle") to the dictionary using the update() method.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

my_dict.update({"city": "Seattle"})

print(my_dict)

Output

{'name': 'James', 'age': 23, 'department': 'Marketing', 'city': 'Seattle'}

Remove Dictionary Items

Python provides different methods to remove items from a dictionary.

You can use the pop() method to remove a particular item in a dictionary. The pop() method removes an item with provided key and returns the value.

In the following example, we will use the pop() method to remove the item with the "age" key from the dictionary.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

x = my_dict.pop("age")
print(x)
print(my_dict)

Output

23 
{'name': 'James', 'department': 'Marketing'}

The popitem() method can be used to remove and return the last inserted (key, value) item (in versions before 3.7, a random item is removed instead).

In the following example, we will use the popitem() method to remove the last item from the dictionary.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

x = my_dict.popitem()
print(x)
print(my_dict)

Output

('department', 'Marketing') 
{'name': 'James', 'age': 23}

You can use the del keyword to remove individual items or the entire dictionary itself.

In the following example, we will use the del keyword to remove the item with the "age" key.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

del my_dict["age"]
print(my_dict)

Output

{'name': 'James', 'department': 'Marketing'}

In the following example, we will use the del keyword to delete the dictionary completely.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

del my_dict

# It will raise an error 
print(my_dict)

Output

NameError  Traceback (most recent call last)
      9 # It will raise an error
---> 10 print(my_dict)

NameError: name 'my_dict' is not defined

The clear() method removes all the items at once from the dictionary.

In the following example, we will use the clear() method to empty the dictionary.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

my_dict.clear()
print(my_dict)

Output

{}

Loop Dictionaries

You can use the for loop to loop through a dictionary.

When looping through a dictionary, the return values are the keys of the dictionary, but there are methods to return also the values.

In the following example, we will print all key names in the dictionary.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

for x in my_dict:
    print(x)

Output

name 
age 
department

In the following example, we will print all values in the dictionary.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

for x in my_dict:
    print(my_dict[x])

Output

James 
23 
Marketing

In the following example, we use the values() method to return the values of a dictionary.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

for x in my_dict.values():
    print(x)

Output

James 
23 
Marketing

In the following example, we will use the keys() method to return the keys of a dictionary.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

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

Output

name 
age 
department

In the following example, we will use the items() method to loop through both keys and values.

my_dict = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing"
}

for x, y in my_dict.items():
    print(x, y)

Output

name James 
age 23 
department Marketing

Copy Dictionaries

When you simply type dictionary_1 = dictionary_2, you don't copy a dictionary, you copy just the reference to dictionary_2, and every change made in dictionary_2 will automatically also be made in dictionary_1. Because the dictionary_1, dictionary_2 are just references to the same object.

There are different ways to copy a dictionary in Python.


Copying Dictionary Element-by-element

To copy a dictionary, you can traverse throughout the whole dictionary and copy each element pointed by the key to a new dictionary already created.

# given dictionary 
dict1 = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing",
    "hobbies": ["calligraphy", "photography", "hiking"]
}

# new dictionary
dict2 = {}

for x in dict1:
    # item by item copying
    dict2[x] = dict1[x] 

print("New copy dict2: ", dict2)

# updating dict2 items and checking the change in dict1
dict2["age"] = 25
dict2["hobbies"] [1] = "painting" # list item updated

print("Updated copy of dict2 : ", dict2)

print("Given dictionay dict1 : ",  dict1)

Output

New copy dict2:  {'name': 'James', 'age': 23, 'department': 'Marketing', 'hobbies': ['calligraphy', 'photography', 'hiking']}
Updated copy of dict2 :  {'name': 'James', 'age': 25, 'department': 'Marketing', 'hobbies': ['calligraphy', 'painting', 'hiking']}
Given dictionay dict1 :  {'name': 'James', 'age': 23, 'department': 'Marketing', 'hobbies': ['calligraphy', 'painting', 'hiking']}

As we can see above, when we updated the "age" key of dict2, the change occurs just on the dict2 dictionary. On the other hand, when we updated the "hobbies" key of dict2, the change occurs in dict1 and 'dict2'. This is because the "honbies" is iterable, and when using the = operator, we copy just the reference, not the whole object.


Copying Dictionary using copy() Method

The dictionary's copy() method returns a shallow copy of the given dictionary. It is similar to what we saw previously in the case of copying elements by traversing through a dictionary.

In the following example, we will do a shallow copy using the copy() method to copy a dictionary.

# given dictionary 
dict1 = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing",
    "hobbies": ["calligraphy", "photography", "hiking"]
}

print("Given Dictionary: ", dict1)

# new dictionary
dict2 = dict1.copy()

print("New copy: " , dict2)

# updating dict2 items and checking the change in dict1
dict2["age"] = 25
dict2["hobbies"] [1] = "painting" # list item updated

print("Updated copy of dict2: ", dict2)

print("Given dictionay dict1: ",  dict1)

Output

Given Dictionary:  {'name': 'James', 'age': 23, 'department': 'Marketing', 'hobbies': ['calligraphy', 'photography', 'hiking']}
New copy:  {'name': 'James', 'age': 23, 'department': 'Marketing', 'hobbies': ['calligraphy', 'photography', 'hiking']}
Updated copy of dict2:  {'name': 'James', 'age': 25, 'department': 'Marketing', 'hobbies': ['calligraphy', 'painting', 'hiking']}
Given dictionay dict1:  {'name': 'James', 'age': 23, 'department': 'Marketing', 'hobbies': ['calligraphy', 'painting', 'hiking']}

In the above code, we use the copy() method to create a shallow copy of "dict1", and we update items and see the corresponding change in the original dictionary. Similar to the case of the element-by-element copying technique, the change in non-iterable items of "dict2" does not have any effect on the original dictionary. However, for iterable items like lists, the change is reflected in the given dictionary, and "dict1" too.


Copying Dictionary using copy.deepcopy() Method

The deepcopy() method is a member of the copy module. This method returns a new dictionary with copied items of the passed dictionary.

The deepcopy() method copies all items of the given dictionary recursively.

In the following example, we will use the deepcopy() method to copy a dictionary.

import copy

# given dictionary 
dict1 = {
    "name": "James" ,
    "age": 23,
    "department":  "Marketing",
    "hobbies": ["calligraphy", "photography", "hiking"]
}

print("Given Dictionary: ", dict1)

# new dictionary
dict2 = copy.deepcopy(dict1)

print("New copy: " , dict2)

# updating dict2 items and checking the change in dict1
dict2["age"] = 25
dict2["hobbies"] [1] = "painting" # list item updated

print("Updated copy of dict2: ", dict2)

print("Given dictionay dict1: ",  dict1)

Output

Given Dictionary:  {'name': 'James', 'age': 23, 'department': 'Marketing', 'hobbies': ['calligraphy', 'photography', 'hiking']}
New copy:  {'name': 'James', 'age': 23, 'department': 'Marketing', 'hobbies': ['calligraphy', 'photography', 'hiking']}
Updated copy of dict2:  {'name': 'James', 'age': 25, 'department': 'Marketing', 'hobbies': ['calligraphy', 'painting', 'hiking']}
Given dictionay dict1:  {'name': 'James', 'age': 23, 'department': 'Marketing', 'hobbies': ['calligraphy', 'photography', 'hiking']}

In the above code, we use the copy.deepcopy() method to create a deep copy of "dict1", and we update items and see the corresponding change in the original dictionary. As we can see from the output, any change in "dict2" is not reflected in "dict1".

The copy.deepcopy() method is useful when we need to copy a dictionary that contains iterable items.


Nested Dictionaries

In Python, a nested dictionary is a dictionary inside a dictionary. It is a collection of dictionaries into one single dictionary.

In the following example, we will create a dictionary that contains three dictionaries.

people = {
1 : {
    "name" : "John",
    "age" : 20
},
2 : {
    "name" : "Stephanie",
    "age" : 22
}
}
people[3] = {}

people[3]["name"] = "Nelson"
people[3]["age"] = 24

print(people)

Output

{1: {'name': 'John', 'age': 20}, 2: {'name': 'Stephanie', 'age': 22}, 3: {'name': 'Nelson', 'age': 24}}

In the following example, we will create three dictionaries and then create one dictionary containing the other three dictionaries.

p1 = {
    "name" : "John",
    "age" : 20
}
p2 = {
    "name" : "Stephanie",
    "age" : 22
}
p3 = {
    "name" : "Nelson",
    "age" : 24
}

people = {
    1 : p1,
    2 : p2,
    3 : p3
}

print(people)

Output

{1: {'name': 'John', 'age': 20}, 2: {'name': 'Stephanie', 'age': 22}, 3: {'name': 'Nelson', 'age': 24}}

Dictionary Methods

Python offers different built-in methods that you can use on dictionaries.

Method Description
clear() It is used to remove all the item from the dictionary
copy() It is used to return a copy of the dictionary
fromkeys() It is used to return a dictionary with the specified keys and value
get() It is used to return the value of the specified key
items() It is used to return a list containing a tuple for each key-value pair
keys() It is used to return a list containing the dictionary's keys
pop() It is used to remove the item with the specified key
popitem() It is used to remove the last inserted key-value pair
setdefault() It is used to return the value of the specified key. If the key does not exist, it will be inserted with the specified value
update() It is used to return the dictionary with the specified key-value pairs
values() It is used to return a list of all the values in the dictionary


ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.