ProGrad Programs
About Us



Dictionaries In Python with Operations & Examples | FACE Prep

Published on 12 Mar 2020

Dictionaries in Python are a collection of key-value pairs that are unordered but indexed. A key-value pair is generally separated by a colon (:) and one key-value pair is separated from another by comma (,).

dictionaries in python

Also, keys in a dictionary must be unique and must be of immutable data types like strings, integers & tuples. Whereas values can be repeated and they can be of any data type. In addition, values are changeable. Let's now look at the Dictionary operations in Python.

a) How to Create Dictionaries in Python

In Python, a dictionary can be created by simply placing all the comma-separated key-value pairs within curly brackets or by using the inbuilt dict () method. For example,

#creating an empty dictionary
dict1 = {}

#creating a dictionary with two key-value pairs
dict1 = {"color":"pink", "shape":"square"}

#creating a dictionary with duplicate values
dict1 = {"color":"pink", "shape":"square", "fav color":"pink"}

#creating a disctionary using dict()
dict1 = dict ({"color":"pink", "shape":"square"})

{'color': 'pink', 'shape': 'square'}
{'color': 'pink', 'shape': 'square', 'fav color': 'pink'}
{'color': 'pink', 'shape': 'square'}

As we have seen above, we are allowed to have duplicate values. But then, how about duplicate keys? What happens when we have duplicate keys in a dictionary?Let's check with this code,

#creating a dictionary with duplicate keys
dict1 = {"color":"pink", "shape":"square", "color":"red"}

{'color': 'red', 'shape': 'square'}

In the above code, we have used the key 'color' twice. Here, at first we have assigned the value "pink" to it and then the value "red", in which the value pink is overwritten by the value red. Hence, when the dictionary is printed, the value red alone gets printed. So, in simple, a key always gets overwritten with the last assigned value and also duplicate keys in a dictionary will lead to loss of values.

Note: Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly. Keys such as "color", "Color", "COLOR", "coLor" will all be treated as unique keys.

Python allows us to create a dictionary inside another dictionary called a Nested dictionary.

Appending Key-Value Pairs to a Dictionary

a) Using update() method

Update method is used to add elements into an empty dictionary or an existing dictionary. In other terms, this method is used to concatenate or join or append two dictionaries in Python.

dict1 = {}
dict2 = {"color": "Blue", "Shape": "Round"}
dict3 = {"size":"small", "length":14cm, "weight":53kg}

#appending to a new dictionary
print (dict1)

#appending a key-value pair to an existing dictionary
dict2.update({"size": "small"})
print (dict2)

#appending or adding two dictionaries
dict3 = {"size":"small", "length":14cm, "weight":53kg}
print (dict2)

{'color': 'Blue', 'Shape': 'Round'}
{'color': 'Blue', 'Shape': 'Round', 'size': 'small'}
{'color': 'Blue', 'Shape': 'Round', 'size': 'small', 'length': '14cm', 'weight': '53kg'}

a) Using Keys

A new value can also be added to a dictionary using a new key. The new key & value need to be inserted using the below format.

#appending key-value pairs to a dictionary
dict1 = {"color":"pink", "shape":"square", "size":"12cm"}
dict1 ["length"] = "14m"
print (dict1)

{'color': 'pink', 'shape': 'square', 'size': '12cm', 'length': '14m'}

Accessing a Value in a Dictionary

a) Using keys

A value in a dictionary can be directly accessed using its keys. For instance,

# accessing a value of a dictionary
dict1 = {"color":"pink", "shape":"square"}
print (dict1 ["shape"])


b) Using get() method

The values in a dictionary can also be accessed using the get() method. The syntax for get () method is shown below.

Syntax: dictionaryname.get ("key")

#accessing a value of a dictionary using get() method
dict1 = {"color":"pink", "shape":"square", "size":12}
print (dict1.get("shape"))


Changing Key-Value Pairs in a Dictionary

A value in a dictionary can be changed or modified or updated using its key. For example,

#changing a value in a dictionary using its key
dict1 = {"color":"pink", "shape":"square"}
dict1 ["color"] = "blue"
print (dict1)

{'shape': 'square', 'color': 'blue'}

Deleting Key-Value Pairs from a Dictionary

a) Using pop() method

The pop() method is used to delete a specified key-value from a dictionary. For instance, let's say you want to delete the key "size" from the below dictionary,

#deleting a value in a dictionary using key
dict1 = {"color":"pink", "shape":"square", "size":"12cm"}

{'color': 'pink', 'shape': 'square'}

b) Using del() method

The del () method can be used to delete a particular value using its key or it can be used to delete the entire dictionary. It can be done this way,

#deleting a value in a dictionary using its key
dict1 = {"color":"pink", "shape":"square", "size":"12cm"}
del dict1 ["color"]

#deleting the entire dictionary
dict1 = {"color":"pink", "shape":"square", "size":"12cm"}
del dict1
print (dict1) #since it is deleted, the output should be an error

{'shape': 'square', 'size': '12cm'}

Traceback (most recent call last):
File "main.py", line 9, in <module>
print (dict1)
NameError: name 'dict1' is not defined

c) Using clear() method

This method can be used to delete all the key-value pairs in a dictionary and return an empty dictionary.

#deleting all the key-value pairs
dict1 = {"color":"pink", "shape":"square", "size":"12cm"}


Slicing in a dictionary

Slicing any object requires an index of the elements. Since indexing is not possible in the dictionary, slicing is also not possible.

Python Methods

Python has a set of inbuilt-methods that help perform certain operations for Dictionaries in Python. Some of them are:

clear()This method removes all the elements from the dictionary
copy()This method returns a copy of the dictionary
pop()This method removes the element (both key & value) with the specified key
popitem()This method removes the last inserted key-value pair
get()This method returns the value of the specified key
values()This method returns a list of all the values in the dictionary
keys()This method returns a list of all dictionary keys
fromkeys()Returns a dictionary with the specified keys and values
has_key()This method returns true if the specified key is present in a dictionary and returns false otherwise
setdefault()This method returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update()Updates the dictionary with the specified key-value pairs
This method compares elements of two dictionaries

How are Dictionaries Better Than Lists in Python?

Even before Dictionaries, you would have learnt about Lists in Python. Have you thought of how or why dictionaries are better than Lists?

Say, for example, you need to check if an element is present in a list or a Dictionary, how would you do it? In a Dictionary, quick retrieval or checking for a key, or its corresponding value is easier. You can do this using the key. Whereas, the same operation in a list would involve a linear search of the complete list, thus making list inefficient for this kind of operation.

Read Next: Nested Dictionaries

If you have any feedback about this article and want to improve this, please write to enquiry@faceprep.in
Explore 'python'