Dictionaries in Python

Dictionaries are one of the four built-in data structures in Python. Dictionaries are data stored in key-value pairs, inside curly brackets.

Keys in dictionaries are used to access data. Thus duplication of keys is not allowed in dictionaries. Otherwise, if two keys are the same, the program won't know which data it Is referring to.

Keys are immutable. The key-value pairing in dictionaries makes the data structure more optimized and disallows polymorphism at the same time.


  1. Ordered - Dictionaries are ordered data structures. They follow a certain order of storage that cannot be changed.
  2. Mutable - Dictionaries are mutable. That is data can be added/ deleted, as well as be modified in a dictionary.
  3. Duplicacy not allowed - Two values cannot be stored in a dictionary using the same key.
  4. Dictionary length - The length of a dictionary can be determined using the len() function.
  5. Data types - Data of any type can be stored in a dictionary.

Creation of a dictionary

The key-value pairs in dictionaries are separated using ':' symbols. Thus a dictionary can be created in several ways.

  1. By simply placing the comma-separated key : value pairs within curly brackets and thereby assign it to a variable
  2. An empty dictionary can be created by declaring empty braces to a variable
  3. By using the dict() constructor method.


d1 = { "a":1, 2:"s", (1,5):[6,9]}
d2 = {}
d3 = dict([("a", 1), (2, "w")])


the outputs being,

{'a': 1, 2: 's', (1, 5): [6, 9]}
{'a': 1, 2: 'w'}

Accessing a dictionary

Like lists, elements in a dictionary can be accessed by placing the keys within square brackets against the variable. The only difference lies in the fact that lists use indexes while dictionaries use keys.

The get() method is used to obtain the value(s) for the key provided within the parenthesis.


  <dictionary variable>.get( <key> )

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


  <dictionary variable>.keys()
The list of keys is a view of the said dictionary and any modification in the dictionary will result in a modification in the keys list as well.

The values() method returns a list of all the values in that dictionary.


  <dictionary variable>.values()
The list of values is a view of the said dictionary and any modification in the dictionary will result in a modification in the values list as well.

The items() function returns the key-value pairs in the dictionary in the form of a list of tuples.


<dictionary variable>.items()
The list of key-value pairs of a dictionary is a view of the said dictionary and any modification in the dictionary will result in a modification in the values list as well.

The 'in' keyword can be used to check whether a particular value is present in a dictionary or not.

d = {1: "a", "g": "b", "p": 20}
if "g" in d:

the output,


Adding/ modifying/ deleting items

There are two methods to add new key-value pairs to an existing dictionary.

  1. An item can be added by simply assigning a new key in square brackets and stating the value.
  2. The update() function can also be used. The new key-value pair can be placed in curly brackets and place as an argument of the update function.

If the key does not exist in the dictionary, then the new key-value pair gets added to it. But if the said key pre-exists in the dictionary, the corresponding value gets updated or modified.

d = { "a": 1, "b": 2}
d["c"] = 3
d.update({"d": 4})
d.update({"a": 5})

the output being,

{"a": 5, "b": 2, "c": 3, "d": 4}

The following methods can be used to delete items from a dictionary or the entire dictionary itself.

  1. The pop() removes the key-value pair corresponding to the key given as an argument to the function.
  2. The popitem() function removes the last inserted item in a dictionary.
  3. The del keyword is similar to the pop() function and can be used to remove a particular key-value pair corresponding to the key mentioned. The del keyword can also be used to delete the dictionary completely.
  4. the clear() method empties a dictionary.
d = {"a": 1, "b": 2, "c": 3}
del d["b"]

the output becomes,

{"a": 1}

Copying Dictionaries

Dictionaries cannot be copied by simply equating a pre-existing dictionary to a new variable. This creates a reference or a shallow copy of the dictionary, and not a true or deep copy.

The copy() function can be used to create a true copy of a dictionary.

d = {"a": 1, "b": 2}
c = d.copy()
c["c"] = 3

which puts out,

{"a": 1, "b": 2}
{"a": 1, "b": 2, "c": 3}

Otherwise, the dict() constructor can also be used to create a copy.

c = dict(d)

Nested dictionaries

Nesting dictionaries refer to the usage of one dictionary as a member of another dictionary. Nesting brings about greater modeling and structuring of data in programming.

Creating nested dictionaries

Nested dictionaries can be created by using dictionaries as values for another bigger dictionary by simply equating them to their corresponding keys.

d1 = { "a": 1, "b": 2}
d2 = {"a": 3, "b": 5, "c": 6}
d3 = {"d1": d1, "d2": d2}


{"d1": { "a": 1, "b": 2}, "d2": {"a": 3, "b": 5, "c": 6}}
Adding elements

Key-value pairs in nested dictionaries can be added in a way similar to matrix indexing in lists,m or indexing in nested lists. The only difference lies in the fact that in this case keys are used instead of indexes.

d = {"d1": { "a": 1, "b": 2}, "d2": {"a": 3, "b": 5, "c": 6}}
d["d3"]["a"] = 7
d["d3"]["b"] = 8


{"d1": { "a": 1, "b": 2}, "d2": {"a": 3, "b": 5, "c": 6}, "d3": {"a": 7, "b": 8}}
Accessing elements

Elements in a nested list can be accessed in a similar way to how elements in a matrix are accessed in the case of lists. The only difference lies in the fact that in this case keys are used instead of indexes.

d = {"d1": { "a": 1, "b": 2}, "d2": {"a": 3, "b": 5, "c": 6}}


Deleting elements

Deleting elements in a nested list is quite similar to deleting elements in a normal dictionary, that is using the pop() method or del keyword.

d = {"d1": { "a": 1, "b": 2}, "d2": {"a": 3, "b": 5, "c": 6}}
del d["d3"]["a"]


{"d1": { "b": 2}, "d2": {"b": 5, "c": 6}}

Dictionary methods

The following are methods that can be used to manipulate and view dictionaries.

Method Description
str() Returns the printable string equivalent of the dictionary
setdefault() Returns the specified value of a key, if not present then inserts the specified key-value pair
has_key() Returns true if the key is present in the dictionary. Else returns false
fromkeys() Returns a dictionary with specified key-value pairs
cmp() Compares between the elements in two dictionaries.

Converting lists to dictionaries

There are several ways to convert one list into dictionaries.

Dictionary comprehension can be used to iterate the elements of a list and add them to the dictionary. The odd elements of the list may be considered to be keys, while the even elements can be considered to be their corresponding values.

d = ["a", 1, "b", 2, "c", 3]
print({d[j]: d[j + 1] for j in range(0, len(d), 2)})


{"a": 1, "b": 2, "c": 3}

Two lists can be converted into a dictionary too. In this case, one list holds the keys, while the other holds the values.

The normal method to do it would be to use an index variable to iterate over the two lists and assign the dictionary key-value pairs in the process.

t1 = ["a", "b", "c"]
t2 = [1, 2, 3]
i = 0
d = {}
while i < len(t1):
    d[t1[i]] = t2[i]
    i = i + 1


{"a": 1, "b": 2, "c": 3}

Dictionary comprehension can also be used to build dictionaries from two lists.

t1 = ["a", "b", "c"]
t2 = [1, 2, 3]
print({t1[i]: t2[i] for i in range(len(t1))})


{"a": 1, "b": 2, "c": 3}

Lists can be created from dictionaries as well. A list of tuples can be created from a dictionary, where each tuple is a key-value pair from the said dictionary. The items() function can be used to access the pairs in the dictionary and the list() constructor can be used to convert it into a list.

d = {"a": 1, "b": 2, "c": 3}


[("a", 1), ("b", 2), ("c", 3)]

Converting tuples to dictionaries

In a way quite similar to lists, tuples can be converted to dictionaries using dictionary comprehension.

t1 = ("a", "b", "c")
t2 = (1, 2, 3)
print({t1[i]: t2[i] for i in range(len(t1))})


{"a": 1, "b": 2, "c": 3}

Dictionaries can be converted into tuples by using the items() function followed by the tuple() constructor in a way similar to the list constructor method.

d = {"a": 1, "b": 2, "c": 3}


[("a", 1), ("b", 2), ("c", 3)]
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions