Python Dictionary

In python, dictionary is a collection of an unordered sequence of key-value pair items. In python, while storing the elements in the dictionary object, you need to make sure that the keys are unique because the dictionary object will allow us to store duplicate values, but the keys must be unique.

 

In python, you can create the dictionary by enclosing the key-value pair items in key: value form within the braces { } and the key-value pair items must be separated by commas.

 

Following is the example of creating the dictionary with different key-value pair items in python.

 

# Dictionary with integer keys
a = {1: 30, 2: 20}
# Dictionary with string keys
b = {"Name": "Suresh", "location": "Hyderabad"}
# Dictionary with mix types
c = {1: "Welcome", "Id": 10}
print("a = ", a)
print("b = ", b)
print("c = ", c)

If you observe the above example, we created different dictionary objects and printed the dictionary object items using the python print method.

 

When you execute the above python dictionary example, you will get the result as shown below.

 

a = {1: 30, 2: 20}
b = {'Name': 'Suresh', 'location': 'Hyderabad'}
c = {1: 'Welcome', 'Id': 10}

Access Dictionary Items

You can access dictionary elements in python, either using the key name inside square brackets [ ] or using the key name inside the get() method.

 

Following is the example of accessing the dictionary elements using key names inside square brackets in python.

 

dct = {"Id": 1, "Name": "Suresh", "Location": "Hyderabad"}
uid = dct["Id"]
name = dct["Name"]
location = dct["Location"]
print("Id = {}, Name = {}, Location = {}".format(uid, name, location))

If you observe the above example, we are accessing elements from the dictionary using different key names with square brackets [ ].

 

The above python dictionary example will return the result as shown below.

 

Id = 1, Name = Suresh, Location = Hyderabad

In python, you can also use key names with the get() method to get or access the dictionary items.

 

Following is the example of accessing the elements from the dictionary using key names with get() method in python.

 

dct = {"Id": 1, "Name": "Suresh", "Location": "Hyderabad"}
uid = dct.get("Id")
name = dct.get("Name")
location = dct.get("Location")
print("Id = {}, Name = {}, Location = {}".format(uid, name, location))

The above python dictionary example will return the result like as shown below.

 

Id = 1, Name = Suresh, Location = Hyderabad

If you try to access the dictionary elements that do not exist with the specified key, you will get that item value as “None”. 

 

dct = {"Id": 1, "Name": "Suresh", "Location": "Hyderabad"}
uid = dct.get("Id1")
name = dct.get("Name1")
location = dct.get("Location1")
print("Id = {}, Name = {}, Location = {}".format(uid, name, location))

The above dictionary example will return the result like as shown below.

 

Id = None, Name = None, Location = None

Change Dictionary Item Values

Using key values, you can change or update the value of the required item in the dictionary.

 

Following is the example of changing the dictionary item values using keys in python.

 

dct = {"Id": 1, "Name": "Suresh", "Location": "Hyderabad"}
print("Before: ",dct)
dct["Id"] = 10
dct["Name"] = "Rohini"
dct["Location"] = "Guntur"
print("After: ",dct)

When you execute the above python dictionary example, you will get the result as shown below.

 

Before: {'Id': 1, 'Name': 'Suresh', 'Location': 'Hyderabad'}
After: {'Id': 10, 'Name': 'Rohini', 'Location': 'Guntur'}

Add Items to Dictionary

In python, you can add items to the dictionary by assigning a value to the new keys.

 

Following is the example of adding items to the dictionary using new keys in python.

 

mbl = {"Brand": "Oneplus", "Model": "8T"}
print("Before: ",mbl)
mbl["Color"] = "Aqua"
mbl["Type"] = "5G"
print("After: ",mbl)

The above python dictionary example will return the result as shown below.

 

Before: {'Brand': 'Oneplus', 'Model': '8T'}
After: {'Brand': 'Oneplus', 'Model': '8T', 'Color': 'Aqua', 'Type': '5G'}

Remove Items from Dictionary

In python, you can delete/remove items from dictionary object using either del keyword, pop(), popitem(), or clear() methods based on our requirements.

 

The del keyword is useful for removing dictionary items with the specified key name or deleting the dictionary completely.

 

Following is the example of using the del keyword to delete the dictionary items with the specified key names in python.

 

mbl = {"Brand": "Oneplus", "Model": "8T", "Color": "Aqua", "Type": "5G"}
print("Before: ",mbl)
del mbl["Color"]
del mbl["Type"]
print("After: ",mbl)

The above python dictionary example will return the result as shown below.

 

Before: {'Brand': 'Oneplus', 'Model': '8T', 'Color': 'Aqua', 'Type': '5G'}
After: {'Brand': 'Oneplus', 'Model': '8T'}

If required, you can also delete the complete dictionary using del keyword in python.

 

mbl = {"Brand": "Oneplus", "Model": "8T", "Color": "Aqua"}
del mbl
print("After: ",mbl)

If you observe the above example, we are deleting the complete list using the del keyword and trying to print the list. The above example will return the result as shown below.

 

Traceback (most recent call last):
  File "D:\pythondic.py", line 4, in <module>
    print("After: ",mbl)
NameError: name 'mbl' is not defined

We got an exception because we tried to print the dictionary (mbl) that is already deleted.

 

In python, the dictionary pop() method is useful to remove the dictionary items based on the specified key name.

 

Following is the example of using the dictionary pop() method to remove the dictionary items.

 

mbl = {"Brand": "Oneplus", "Model": "8T", "Color": "Aqua", "Type": "5G"}
print("Before: ",mbl)
mbl.pop("Color")
mbl.pop("Type")
print("After: ",mbl)

When you execute the above python dictionary program, you will get the result as shown below.

 

Before: {'Brand': 'Oneplus', 'Model': '8T', 'Color': 'Aqua', 'Type': '5G'}
After: {'Brand': 'Oneplus', 'Model': '8T'}

Instead of using dictionary keys, you can use popitem() method in python to delete or remove the last inserted item. 

 

mbl = {"Brand": "Oneplus", "Model": "8T", "Color": "Aqua"}
print("Before: ",mbl)
mbl.popitem()
print("After: ",mbl)

The above python dictionary example will return the result as shown below.

 

Before: {'Brand': 'Oneplus', 'Model': '8T', 'Color': 'Aqua'}
After: {'Brand': 'Oneplus', 'Model': '8T'}

If you want to clear or empty dictionary items, you can use the dictionary clear() method.

 

Following is the example of removing all the dictionary items using the clear() method in python.

 

mbl = {"Brand": "Oneplus", "Model": "8T", "Color": "Aqua"}
print("Before: ",mbl)
mbl.clear()
print("After: ",mbl)

The above python dictionary example will return the result as shown below.

 

Before: {'Brand': 'Oneplus', 'Model': '8T', 'Color': 'Aqua'}
After: {}

Dictionary Length

In python, to count the number of items (key-value pairs) in the list, use the len() function.

 

Following is the example of using len() function in python to get the dictionary length/size.

 

mbl = {"Brand": "Oneplus", "Model": "8T", "Color": "Aqua"}
print("Dictionary Size: ", len(mbl)) #Dictionary Size: 3

By using len() function, you can also check whether the dictionary is empty or not like as shown below. 

 

mbl = {}
count = len(mbl)
if count > 0:
   print("Dictionary size: ", count)
else:
    print("Dictionary is empty")

The above dictionary example will return the result as shown below.

 

Dictionary is empty

Join or Concatenate Dictionaries

You can use an update() method to join or merge multiple dictionaries with all the list elements in python.

 

Following is the example of joining the dictionaries using the update() method in python.

 

dct1 = {1: 10, 2: 20}
dct2 = {"name": "suresh", "location": "guntur"}
dct1.update(dct2)
print(dct1)

The above list example will return the result as shown below.

 

{1: 10, 2: 20, 'name': 'suresh', 'location': 'guntur'}

If two dictionaries (dct1, dct2) have the same keys, the update() method will consider using the values of the second dictionary (dct2).

 

Following is the example of merging the two dictionaries with the same keys using the update() method in python.

 

dct1 = {1: 10, 2: 20, "location": "guntur"}
dct2 = {1: 30, "name": "suresh", "location": "guntur"}
dct1.update(dct2)
print(dct1)

The above dictionary example will return the result as shown below.

 

{1: 30, 2: 20, 'location': 'guntur', 'name': 'suresh'}

Check If Dictionary has Key

By using in and not in operators, you can check whether the specified key exists in the dictionary or not.

 

Following is the example to verify whether the dictionary has specified keys or not using in operator in python.

 

dct = {1: 10, "name": "suresh", "location": "guntur"}
print("1 in dict: ", 1 in dct)
print("name in dict: ", "name" in dct)
print("50 in dict: ", 50 in dct)

The above dictionary example will return the result as shown below.

 

1 in dict: True
name in dict: True
50 in dict: False

Python Iterate through Dictionary

By using for loop, you can iterate through the items of the dictionary in python. While iterating over dictionary items, it will return only the keys of the dictionary.

 

Following is the example of looping through the dictionary items in python to get all dictionary keys using for loop.

 

dct = {1: 10, "name": "suresh", "location": "guntur"}
for item in dct:
    print(dct[item])

The above dictionary example will return the result as shown below.

 

1
name
location

If you want to get all the dictionary values, you need to use the dictionary object's key names, as shown below.

 

dct = {1: 10, "name": "suresh", "location": "guntur"}
for item in dct:
    print(dct[item])

The above dictionary example will return the result as shown below.

 

10
suresh
guntur

Python Copy Dictionary

In python, you can copy a dictionary either using the dictionary copy() method or dict() method, but copying the dictionary like dic2 = dic1 is not allowed because the dic2 will reference dic1. So, the changes you made in dic1 will automatically reflect in dic2.

 

Following is the example of using the dictionary copy() method to copy a dictionary in python.

 

dic1 = {1: 10, "name": "suresh", "location": "guntur"}
dic2 = {}
print("====Before Copy====")
print("Dict1: ", dic1)
print("Dict2: ", dic2)
dic2 = dic1.copy()
print("====After Copy====")
print("Dict1: ", dic1)
print("Dict2: ", dic2)

The above dictionary example will return the result as shown below.

 

====Before Copy====
Dict1: {1: 10, 'name': 'suresh', 'location': 'guntur'}
Dict2: {}
====After Copy====
Dict1: {1: 10, 'name': 'suresh', 'location': 'guntur'}
Dict2: {1: 10, 'name': 'suresh', 'location': 'guntur'}

Following is the example of using the built-in dict() method to copy a dictionary in python.

 

dic1 = {1: 10, "name": "suresh", "location": "guntur"}
dic2 = {}
print("====Before Copy====")
print("Dict1: ", dic1)
print("Dict2: ", dic2)
dic2 = dict(dic1)
print("====After Copy====")
print("Dict1: ", dic1)
print("Dict2: ", dic2)

The above dictionary example will return the result as shown below.

 

====Before Copy====
Dict1: {1: 10, 'name': 'suresh', 'location': 'guntur'}
Dict2: {}
====After Copy====
Dict1: {1: 10, 'name': 'suresh', 'location': 'guntur'}
Dict2: {1: 10, 'name': 'suresh', 'location': 'guntur'}

Python Nested Dictionary

In python, you can create a nested dictionary by adding one dictionary inside of another dictionary.

 

Following is the example of creating the nested dictionary in python.

 

cars = {
    "car1": {
        "brand": "hyundai",
        "name": "i10"
        },
    "car2": {
        "brand": "kia",
        "name": "sonet"
       }
    }
print(cars)

The above dictionary example will return the result as shown below.

 

{'car1': {'brand': 'hyundai', 'name': 'i10'}, 'car2': {'brand': 'kia', 'name': 'sonet'}}

If you want, you can also create a nested dictionary, as shown below.

 

car1 = {"brand": "hyundai", "name": "i10"}
car2 = {"brand": "kia", "name": "sonet"}
cars = {
    "car1": car1,
    "car2": car2
    }
print(cars)

Python Sort Dictionary Elements

In python, the sorted() method will sort the dictionary elements based on the keys and values. By default, the sorted() method will sort the list elements in ascending order.

 

Following is the example of sorting the dictionary elements in ascending order using keys in the sorted() method.

 

dct = {4: 10, 1: 20, 5: 30, 3: 60}
# print sorted dictionary keys
print(sorted(dct.keys()))
# print sorted dictionary items
print(sorted(dct.items()))

The above dictionary example will return the result as shown below.

 

[1, 3, 4, 5]
[(1, 20), (3, 60), (4, 10), (5, 30)]

Following is the example of sorting the dictionary elements in ascending order using values in the sorted() method. 

 

dct = {4: 10, 1: 20, 5: 30, 3: 60}
# print sorted dictionary values
print(sorted(dct.values()))

The above dictionary example will return the result as shown below.

 

[10, 20, 30, 60]

To sort the dictionary elements in descending order, you need to use the optional reverse = True property with sorted() method like as shown below.

 

dct = {4: 10, 1: 20, 5: 30, 3: 60}
# print sorted dictionary keys
print(sorted(dct.keys(), reverse = True))
# print sorted dictionary items
print(sorted(dct.items(), reverse = True))

The above dictionary example will return the result as shown below.

 

[5, 4, 3, 1]
[(5, 30), (4, 10), (3, 60), (1, 20)]

To sort dictionary items either in ascending or descending order, you need to make sure that all the dictionary keys/values must be the same type; otherwise, you will get a TypeError exception.

 

dct = {4: 10, 1: 20, "name": "suresh", "location": "guntur"}
# print sorted dictionary keys
print(sorted(dct.keys(), reverse = True))
# print sorted dictionary values
print(sorted(dct.values(), reverse = True))

The above python dictionary example will return the result as shown below.

 

Traceback (most recent call last):
  File "D:\pythondict.py", line 2, in <module>
    for item in sorted (dic):
TypeError: '<' not supported between instances of 'str' and 'int'

Python Dictionary Methods

In python, the dictionary object has a set of built-in methods to perform different operations like adding items to the dictionary, removing elements from the dictionary, etc., based on your requirements.

 

Following are the built-in dictionary functions available in the python programming language.

 

MethodDescription
get() It is useful to get the value of the specified key.
items() It will return a list with key-value pairs.
keys() It will return the list of all the keys in the dictionary.
fromkeys() It will return the dictionary with the specified keys.
values() It will return the list of all the values in the dictionary.
pop() It is useful to remove the element at the specified key.
popitem() It will remove the last inserted element.
clear() It is useful to remove all the elements of a dictionary.
update() It will update the dictionary with the specified key-value pairs.
copy() It is useful to return a copy of the dictionary.
setdefault() It will return the value of the specified key. If the key is not found, the default value will be returned.