Python ProgrammingPython Programming

Python Dictionaries

In this tutorial you will learn, what is a dictionary data type and when to use it in Python.

A dictionary is an arbitrary collection of objects that are indexed by immutable objects, such as strings or numbers. Dictionaries in Python are like associative arrays of Php or hash tables of Java or maps of Golang.
Dictionaries access values by means of integers, strings, or other Python objects called keys, which indicate where in the dictionary a given value is found.
A dictionary maps keys to values. Dictionaries are mutable objects.


Create and Print a Dictionary

There are quite a few different ways to create a dictionary, so let's take a simple example of how to create a dictionary equal to {'Canada': 100, 'Japan': 500} in five different ways.

Example
Create and print a dictionary:
d1 = dict(Canada=100, Japan=500)
d2 = {'Canada': 100, 'Japan': 500}
d3 = dict(zip(['Canada', 'Japan'], [100, 500]))
d4 = dict([('Canada', 100), ('Japan', 500)])
d5 = dict({'Japan': 500, 'Canada': 100})
print(d1)
print(d2)
print(d3)
print(d4)
print(d5)   
 
Output
{'Canada': 100, 'Japan': 500}
{'Canada': 100, 'Japan': 500}
{'Canada': 100, 'Japan': 500}
{'Canada': 100, 'Japan': 500}
{'Canada': 100, 'Japan': 500}

Create an Empty Dictionary

A simple code creates a new empty dictionary and assigns it to d1. After you create a dictionary, you may store values in it.

Example
Create and print an empty dictionary:
d1 = {}
d1[0] = "Canada"
d1[1] = "Japan"
print(d1)
Output
{0: 'Canada', 1: 'Japan'}

Access Dictionary Items

To access any particular item of a dictionary we need to refer it by its key name, inside square brackets or by using get() method.

Example
Get the value of the "Canada" and "Japan" key:
d1 = {'Canada': 100, 'Japan': 500}
x = d1["Canada"]
y = d1.get("Japan")
print(x)
print(y)
Output
100
500

Change Item Value

To update value of any particular item of a dictionary we need to refer it by its key name, inside square brackets.

Example
Change the "Canada" from 100 to 200:
d1 = {'Canada': 100, 'Japan': 500}
print(d1["Canada"])
d1["Canada"] = 200
print(d1["Canada"])
Output
100
200

Adding Items to Dictionary

Using a new index key and assigning a value to it we can add an item to existing created dictionary.

Example
Adding items "Germany" and "Japan":
d1 = {'Canada': 100, 'Japan': 500}
print(d1)
d1["Germany"] = 600
d1["Italy"] = 400
print(d1)
Output
{'Canada': 100, 'Japan': 500}
{'Italy': 400, 'Canada': 100, 'Germany': 600, 'Japan': 500}

Removing Items from Dictionary

The pop() method and del keyword removes the item with the specified key name. However, the popitem() method removes the last inserted item.

Example
pop() removes "Canada", del removes "Germany" and popitem() will remove either "Japan" or "Italy":
d1 = {'Canada': 100, 'Japan': 200, 'Germany': 300, 'Italy': 400}
d1.pop("Canada")
del d1["Germany"]
d1.popitem()
print(d1)
Output
{'Japan': 200}

Delete or Truncate a Dictionary

The del keyword without the specified key name can delete the dictionary completely and clear() keyword delete all items the dictionary.

Example
Dictionary d1 deleted by del and d2 truncated by clear():
d1 = {'Canada': 100, 'Japan': 200, 'Germany': 300, 'Italy': 400}
del d1
d2 = {'Canada': 100, 'Japan': 200, 'Germany': 300, 'Italy': 400}
d2.clear()
print(d2)

Iterate over Dictionaries using for loops

A for loop is generally used to get keys and values of a dictionary. The items() function returns both values and keys. The values() function only return values of a dictionary.

Example
d1 = {'Canada': 100, 'Japan': 200, 'Germany': 300, 'Italy': 400}
 
# Example 1 Print only keys
print("*" * 10)
for x in d1:
    print(x)
 
# Example 2 Print only values
print("*" * 10)
for x in d1:
    print(d1[x])
 
# Example 3 Print only values
print("*" * 10)
for x in d1.values():
    print(x)
 
# Example 4 Print only keys and values
print("*" * 10)
for x, y in d1.items():
    print(x, "=>", y)
 
Output
**********
Canada
Italy
Germany
Japan
**********
100
400
300
200
**********
100
400
300
200
**********
Canada => 100
Italy => 400
Germany => 300
Japan => 200

Check if Key exists in Dictionary

The in keyword is used to verify if a specified key is present in a dictionary.

Example
d1 = {'Canada': 100, 'Japan': 200, 'Germany': 300, 'Italy': 400}
 
if 'Japan' in d1:
    print('Yes')
else:
    print('No')
Output
Yes

Find Length of a Dictionary

The len() method is used to find number of keys in a dictionary.

Example
d1 = {'Canada': 100, 'Japan': 200, 'Germany': 300, 'Italy': 400}
print(len(d1))
Output
4

Sort a Dictionary by Key

The sorted() method is used to sort items of a dictionary.

Example
d1 = {'Canada': 100, 'Japan': 200, 'Germany': 300, 'Italy': 400}
 
for key in sorted(d1):
    print("%s: %s" % (key, d1[key]))
Output
Canada: 100
Germany: 300
Italy: 400
Japan: 200

Merge two Dictionaries

The update() method is used to merge items of two dictionaries.

Example
d1 = {'Canada': 100, 'Japan': 200, 'Germany': 300, 'Italy': 400}
d2 = {'Australia': 500, 'India': 600}
 
d2.update(d1)
print(d1)
print(d2)
Output
{'Germany': 300, 'Italy': 400, 'Canada': 100, 'Japan': 200}
{'Australia': 500, 'Canada': 100, 'Germany': 300, 'Italy': 400, 'India': 600, 'Japan': 200}

Sort a Dictionary by Value

Example
d1 = {'Canada': 300, 'Japan': 400, 'Germany': 100, 'Italy': 200}
 
for x in sorted(d1, key=d1.get):
    print(x, d1[x])
Output
Germany 100
Italy 200
Canada 300
Japan 400