Hello geeks, in this python 3 tutorial, you are going to learn A to Z of Python dictionary. We will discuss the followings:

  • What is Python Dictionary?
  • How to create a Dictionary!
  • Add, Delete, Update Elements.
  • Access Elements of a Dictionary.
  • Merging Two Dictionaries
  • Creating Nested Dictionary
  • Adding, Deleting, Updating elements in a Nested Dictionary.
  • Different Methods of Python Dictionary.
  • copy(), fromkeys(), get(), pop(), popitem(), items(), keys(), values()

So, without further ado let’s jump into it.

What is Python Dictionary?

Python dictionary is a data type of python programming language. It stores data by mapping them with a key. Data are stored in “Key-Value” pairs where each “Key” must be unique. Lists, Tuples can also be stored as value in a dictionary.

How to create a dictionary?

We use a descriptive name and curly-braces to create a dictionary. Keys & Values are separated by a (:) colon. Each ‘key:value’ pair is separated by comma (,) It is a data structure too.

a = {} #an empty dictionary.

book_details = {
“name”:”The Seven Habits Of Highly Effective People”,
“author”: “Stephen R Covey”,
“publication”: “Pocket Books”
}

We can create a dictionary by using python’s built in dict() function.

a = dict()

Access Python Dictionary

We can access the values of elements of a dictionary using square brackets []. We pass the ‘key’ of a specific element and python returns the value assigned with that key.

if we want only the name of the book from above example…

print("book_name:", book_details ['name'])

That line of code will generate the output below.

book_name: The Seven Habits Of Highly Effective People

You will have to be concerned about one issue. If you pass a key that is not present in the dictionary, python will return a “KeyError” exeception.

Add & Update

Adding & Updating a python dictionary is a piece of cake. Dictionary is a mutable data type. It means we can add new elements and update an existing one of a dictionary. Assume that we want to add the ‘year_of_publication’ in our ‘book_details’ dictionary and change the ‘publication’ name. Here, ‘year_of_publication’ will be added and ‘publication’ will be updated.

book_details['year_of_publication'] =1989 #Adding New Value

#Updating Existing Value

book_details['publication'] = 'Free Press' 

Delete

We can do three different delete operations in a dictionary.

  • An element
  • All elements
  • The dictionary

To delete an element of a dictionary we use del statement. The expression is

del book_details['year_of_publication']

To delete the ‘year_of_publication‘ from ‘book_details‘ dictionary the code will be…

del book_details['year_of_publication']

Now to delete all the elements of a dictionary we use clear() function.

book_details.clear()

This statement will delete all the elements and make it an empty dictionary.

Sometimes we do not need the dictionary once we used it. So, there is no benefits of letting an empty dictionary eat our memory. In these cases, we should delete the entire dictionary. We use del statement as before but only with the ‘dictionary_name’

del dictionary_name
del book_details

Now, if you want to access the dictionary a “NameError” exception will be shown. Because there left no dictionary of that name.

Merging Two Dictionaries

In python there are several ways of merging two dictionaries;

  • update()  method
  • **[double star]
  • “|” union operator (introduced in python 3.9)
  • |= update.(introduced in python 3.9)

update() method

Suppose, we have two dictionaries named books & books_of_programming. We want to add the books_of_programming in books. In that case we can use update() function. Because this method will merge the dictionaries without creating a new one.

books = {
        "name":"The Seven Habits Of Highly Effective People",
        "author": "Stephen R Covey",
        "publication": "Pocket Books",

}

books_of_programming = {
        "name2":"Think Python",
        "author2": "Allen B. Downey",
        "publication2": "O'REILLY",
}

books.update(books_of_programming)
print(books)

In that case you will have to remember that the keys of the dictionaries don’t match.Otherwise you may see unexpected output.

**[double star]

Using ** we can merge arbitrary number of dictionaries. .** [double star] is a shortcut that allows you to pass multiple arguments to a function directly using a dictionary. When we apply ** to a dictionary, it expands the contents in dictionary as a collection of key value pairs.

other_books = {
    "name3":"The legacy of Blood",
    "author3":"Anthony Mascarenhas",
    "publication3": "Hodder & Stoughton",
}
all_books = {**books, **books_of_programming, **other_books}

This single line expression will merge all three dictionaries.

“|” union operator

In python 3.9 a new operator is introduced to merge dictionaries which is called union operator. (|) union operator merges two dictionaries. But it preserves the original dictionary.

books | books_of_programming

|= update.

This is for in-place merging of dictionaries. This merges two dictionaries by updating the value of  the left one.

books |= books_of_programming

Nested Dictionary

Till now we were working with a single dictionary. What if we store a dictionary inside a dictionary!!! A dictionary inside another dictionary is called a nested dictionary. In a nested dictionary the value of an element is also a dictionary. The key of the element work as the name of the dictionary. Now we will store more books’ data inside the dictionary named ‘books’.

books = {
   "book1": {
        "name":"The Seven Habits Of Highly Effective People",
        "author": "Stephen R Covey",
        "publication": "Pocket Books",
    },
    "book2":{
        "name":"The Alchemist",
        "author": "Paulo Coelho",
        "publication": "HarperTorch",
    }
}

print(books['book2']['publication'])

To access the values of a nested dictionary we should use the parent key(in here ‘book1 or book2’). Then the key of the child dictionary(name, author, publication). The expression will look like this:

dictionary_name[parent_key][child_key]

There is no limitation of using nested dictionaries. You can use as many layers as you want.

Add & Update Nested Dictionary

Adding & Updating nested dictionary are almost similar to a single dictionary adding & updating. As we discussed the method of accessing values of a nested dictionary we follow the same procedure during adding and updating.

#Adding New Value
books['book1']['year_of_publication'] = 1989   

#Updating Existing Value
books['book1']['publication'] = 'Free Press'   

Delete From Nested Dictionary

The three methods of deleting elements from dictionary are also applicable in nested dictionary. So, without describing it twice enjoy the taste of it…

#will delete the specific element
del books['book1']['year_of_publication'] 
books['book1'].clear() #will clear the ['book1'] dictionary.
del books['book1'] #will delete the ['book1'] dictionary

Different Methods of Python Dictionary

There are many methods.

Methods Description
clear() Removes all Items
copy() Returns Shallow Copy of a Dictionary
formkeys() creates dictionary from given sequence
get() Returns Value of The Key
items() returns view of dictionary’s (key, value) pair
keys() Returns View Object of All Keys
pop() removes and returns element having given key
update() Updates the Dictionary
values() returns view of all values in dictionary
setdefault() Inserts Key With a Value if Key is not Present
popitem() Returns & Removes Latest Element From Dictionary

copy()

copy() method is used to make a shallow duplicate of a dictionary. copy() doesn’t take any arguments. Let’s make a copy of our books dictionary:

new_dict = books.copy()

fromkeys()

This method creates a new dictionary from a given sequence. It takes two parameters “sequence” & “value”.The ‘sequence’ is a required parameter. The values inside the sequence are taken as the keys of the new dictionary and the data contained by “value” parameter is assigned to the keys.

The expression looks like this:

dictionary.fromkeys(sequence[, value])
keys = {1,2,3,4,5}
value = 'null'

new_dict = dict.fromkeys(keys,value)

print(new_dict)

if you don’t pass the ‘value’ parameter; By default the value of the dictionary elements will be ‘None’

get()

The get() method is used to fetch the value of a specific element. It uses the ‘key’ of that element. If key is absent in the dictionary it will return ‘None’ by default. get() takes two arguments. Key & Value. If the key is absent in the dictionary it will return the data of value parameter instead of “None”.

dictionary = {
    1:"Arabi",
    2:'Ahbab',
    3:"Awan"
}
print(dictionary.get(1,"Not Found"))
print(dictionary.get(4))
print(dictionary.get(4,"Not Found"))

Output:

Arabi
None
Not Found

pop()

It picks up the element from the dictionary. The value of the element  is returned and  the element is removed. It takes two parameters.

dictionary.pop(keyname, defaultvalue)
dictionary = {
    1:"Arabi",
    2:'Ahbab',
    3:"Awan"
}
x = dictionary.pop(2,'Not Found')
z = dictionary.pop(4,'Not Found')
print(x)
print(z)
print(dictionary)

Output:

Ahbab
Not Found
{1: 'Arabi', 3: 'Awan'}

popitem()

It works same as pop(). The only difference is that we had to pass the key in pop() method. But ‘popitem()’ doesn’t take any ‘key’ as parameter. It returns and removes the latest (last inserted) item of the dictionary.

x = dictionary.popitem()
print(x)

Output:

(3, 'Awan')

items(), keys(), values()

These three methods return different data. But they work in the same way. The items() function returns all the items of a dictionary. The keys() function returns all the keys of the dictionary & values() returns all the values of the dictionary. None of them takes any parameter.

print(dictionary.items())
print(dictionary.keys())
print(dictionary.values())

Output:

dict_items([(1, 'Arabi'), (2, 'Ahbab'), (3, 'Awan')])
dict_keys([1, 2, 3])
dict_values(['Arabi', 'Ahbab', 'Awan'])
+ posts

Author | Python-Django Developer

+ posts

Full-stack Developer (Python | Django | React | React-Native | Angular | Vue)