Python Dictionary And Nested Dictionary With Example

We have already gone through python list and python set. Now, we will go through python dictionary and nested dictionary. We will see what is dictionary, how to create it?, how to add item to it, how delete or modify in dictionary etc.

Getting Started

Dictionaries in Python are mutable and unordered collections. They come from built-in data structure and contain elements in the form of a key : value pairs that associate keys to values.

Dictionaries in Python are containers that contains pairs of keys and their corresponding values. Keys must be immutable and unique in Python dictionaries unlike values which are mutable and can be present multiple times with different keys.

In others languages, dictionaries in Python are known as associative arrays or hash tables.

Create Dictionary in Python

In Python language, Dictionaries are complex containers that can be created through numerous ways. It can be created by using :

  • Using Curly Bracket i.e. { }

    In Python, we use curly bracket {} to create dictionary. It marks the beginning and the end of dictionary. All pair of keys and values are included within curly bracket. Keys are separated from their corresponding values by colon : and each pair key : value is separated from another by comma ,.

    day = { "key_1" : "value_1", "key_2" : "value_2"}
    

    Here,
    we have defined a dictionary using curly bracket that have two pair of keys and values – key_1: value_1 and key_2: value_2.

  • Dictionary Comprehension in Python

    Dictionary comprehension is also used to create dictionary in Python.

    A dictionary comprehension takes the form

    {key: value for (key, value) in iterable}
    

    Here, we are trying to create dictionary from iterable using pairs of key: values present in it.

    For example,

    day = [ "monday" , "tuesday" , "wednesday", "thursday", "friday"] 
    my_dict = { key : value for key, value in enumerate(day) }
    print (my_dict)
    

    Output:

    {0: 'monday', 1: 'tuesday', 2: 'wednesday', 3: 'thursday', 4: 'friday'}
    

    my_dict contains pairs of key: values from list day by using enumerate function. Keys are position at which corresponding values are present in list day.

  • Using dict() Constructor

    dict() is a constructor which can also be used to create dictionary. It can be used as below –

    dict_name = dict(key_1=value_1, ...)
    

    As shown above, dict() is used to build dictionaries directly from sequences of key-value pairs in Python.

    Let’s see how it works.

    moment = dict(year=2022, month="April", day="wednesday", hour="16h pm")
    print(moment)
    

    Output:

    {'year': 2022, 'month': 'April', 'day': 'wednesday', 'hour': '16h pm'}
    

    Here,
    moment is a dictionary created using dict() constructor that have pairs of key: value

    1. ‘year’: 2022
    2. ‘month’: ‘April’
    3. ‘day’: ‘wednesday’
    4. ‘hour’: ’16h pm’

    Create Empty Dictionary in Python

    Note : We can use python internal function – dict() to create an empty dictionary in Python.

    For example,

     
    y = dict()
    

    Here, y is an empty dictionary created using dict() function.

    We will show now another example of using dict() constructor.

    Using zip() with dict() Constructor to Create Dictionary

    zip() function returns a zip object where passed iterators are used to create tuple by grouping first and second iterators.

    We can use returned zip object to create tuples as shown below –

    moment = dict(zip(("year", "month", "day", "hour"), (2022, "April", "wednesday", "16h
    pm")))
    print(moment)
    

    Output:

    {'year': 2022, 'month': 'April', 'day': 'wednesday', 'hour': '16h pm'}
    

    As explained above, zip() is Python function which takes arguments as two iterables objects and associate each item in the first iterable to its corresponding item in the second iterable. If two iterable objects have different length, length of shorter iterable object decides length of returned object.

    Creating Dictionary using list and dict() Constructor

    dict() constructor can be also be used with list to create dictionary as shown below –

    moment = dict([ ["year", 2022], ["month", "April"], ["day", "wednesday"], ["hour", "16h pm"] ])
    print(moment)
    

    Output:

    {'year': 2022, 'month': 'April', 'day': 'wednesday', 'hour': '16h pm'}
    

Get Length of Dictionary in Python

We can get length of dictionary in python using len() internal function.

day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
print(len(day))

Output:

5

Note : len() returns the number of keys present in a dictionary. Thus, the number of keys involves to dictionary length.

Get Type of Dictionary in Python

We got the size of dictionary in python using len() function. Now, we will get type of created dictionary. To do that we are going to use the Python internal function – type().

Note : type() is a function which help us to get the type of any created object in Python. It accepts dictionary as argument and returns type of dictionary.

For example,

day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
print(type(day))

Output:

class 'dict'

Access Items of Dictionary in Python

Items of Dictionary in Python can be accessed in two ways –

  1. Access all items at Once Using name of Dictionary
  2. Access Value of Any Item Using It’s Key
  • Access all items at Once

    In Python a simpler way to access a dictionary entirely is to display it by using its name.

    For example,

    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
    print(day)
    

    Output:

    { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
    

    Here, all items have been displayed using dictionary’s name.

  • Access Value of Any Item

    In another way we can access a particular value of the dictionary by providing its key in square brackets in double quote.

    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
    print(day["monday" ])
    

    Output:

    1
    

    Note : If the key in the square bracket is not present in the dictionary an error will be displayed.

Get keys of Dictionary in Python

All keys present in a created Dictionary can be accessed using keys() method. This method returns an object containing a list of keys present in the dictionary.

day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
print(day.keys())

Output:

dict_keys(['monday', 'tuesday', 'wednesday', 'thursday', 'friday'])

Note : The result of this output can be converted in a list object by using the Python internal function list() .

newList = list((day.keys())) 
print(newList)

Output:

['monday', 'tuesday', 'wednesday', 'thursday', 'friday']

Get Values of Dictionary in Python

When we want to get all the values present in created Dictionary, we use values() method which returns an object containing the list of values present in Dictionary.

day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5} 
print(day.values())

Output:

dict_values([1, 2, 3, 4, 5])

As we say above we can convert this output in a list object by using list() function.

newList = list((day.values())) 
print(newList)

Output:

[1, 2, 3, 4, 5]

Get All Items of Dictionary.

Like keys and values we can also get all the items present in Dictionary. Items of dictionary can be accessed –

  1. Using items() Method
  2. Using For Loop
  1. Using items() Method

    To access items, we will use the dictionary method called items(). For example,

    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
    print(day.items())
    

    Output:

    dict_items([('monday', 1), ('tuesday', 2), ('wednesday', 3), ('thursday', 4), ('friday', 5)])
    

    Note : items() method returns an object that contains a list of tuple pair (key : value). So, let’s convert this output into list object.

    newList = list((day.items())) 
    print(newList)
    

    Output:

    [('monday', 1), ('tuesday', 2), ('wednesday', 3), ('thursday', 4), ('friday', 5)]
    
  2. Using For Loop

    Another way to access all items present in a dictionary is to make an iteration through the dictionary like the example below.

    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5} 
    for key in day :
        print(key, " : ", day[key], end= " ")
    

    Output:

    monday : 1 tuesday : 2 wednesday : 3 thursday : 4 friday : 5
    

Checking if Any Key Exist or Not

Here our purpose is to verify if any key is present in a python dictionary or not. To achieve this goal, we are going to use the operator in and not in. It results a boolean value i.e. True or False. We will get True if the condition is verified. Otherwise, it’s False.

  • Using in Operator

    in operator returns True if given key is present in dictionary, else it returns False. For example,

    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
    print("monday" in day)
    

    Output:

    True
    

    Here, we checked if monday key is present in given dictionary – day or not. Since it’s present in dictionary, in returns True. Hence, output is True.

  • Using not in Operator

    not in operator returns True if given key is not present in dictionary, else it returns False. For example,

    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5} 
    print("monday" not in day)
    

    Output:

    False
    

    monday key is present in dictionary – day. So, not in operator returns False. Hence, output is False.

    Let’s take another example,

     
    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5} 
    print("saturday" not in day)
    

    Output:

     
    True 
    

    saturday key is not present in dictionary. So, not in operator returns True. Hence, output is True.

    Let’s check another example,

     
    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
    print("tuesday" not in day)
    

    Output:

     
    False
    

    Again, tuesday is present in dictionary. So, output is False.

Till now, we checked if key of dictionary is present in python dictionary or not.

We can also check if any value is present in Dictionary or not. Let’s check it with some python code.

Checking if any value Exists or Not

We can use values() method and in operator to check if any value exist in dictionary or not.

 
day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5} 
newList = list(day.values())
print(0 in newList)

Output:

 
False

Here,

  1. values() returns all values present in dictionary.
  2. Then, we applied in operator on returned values which checks if given value is present in list or not.
  3. Since 0 is not present in values. Hence, output is False.

Let’s take another example,

 
day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5} 
newList = list(day.values())
print(2 in newList)

Output:

 
True

Here,
We checked if 2 is present in dictionary’s values or not. Since it is present. Output is True.

Add Item in Dictionary

To add new element (key : value) to a dictionary, we use the syntax below.

 
dictionary name [new key] = value

For example,

 
day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5} 
day["saturday"] = 6
print(day) 

Output:

 
{'monday': 1, 'tuesday': 2, 'wednesday': 3, 'thursday': 4, 'friday': 5, 'saturday': 6}

Update Item in Dictionary

In Python dictionary, we update value of existing item (key : value) by using the following syntax –

 
dictionary name [existing key ] = new value

For example,

 
day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
day["monday" ] = 0
print(day) 

Output:

 
{'monday': 0, 'tuesday': 2, 'wednesday': 3, 'thursday': 4, 'friday': 5, 'saturday': 6}

Here,
We updated value of key monday to 0 from 1.

Note : The syntax used to add and update item in a dictionary are almost the same but for adding item the key must be a new key and for updating item the must be an existing key and the value must be new value.

Update a Dictionary

We can also update a dictionary in Python. To do that we are going to add a dictionary to another dictionary by using the dictionary method called update().

For example,

 
day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
week = {"saturday" : 6, "sunday" : 7 }
day.update(week)
print(day) 

Output:

 
{'monday': 1, 'tuesday': 2, 'wednesday': 3, 'thursday': 4, 'friday': 5, 'saturday': 6, 'sunday': 7}

Remove Item in Dictionary

After creating a Dictionary, we have the choice to remove any of its item. To remove item in dictionary, we use different methods or keyword. They are –

  1. Using pop() Method
  2. Using popitem() Method
  3. Using del keyword
  4. Using clear() method
  1. Using pop() Method

    pop() method removes specified key and returns its corresponding value. For example,

     
    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
    day.pop("wednesday")
    print(day)
    

    Output:

     
    {'monday': 1, 'tuesday': 2, 'thursday': 4, 'friday': 5}
    

    Here,
    wednesday has been removed using pop() method from dictionary day.

  2. Using popitem() Method

    popitem() takes no argument and removes the last item in Dictionary and returns it. Raises a keyError when dictionary is empty. For example,

     
    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
    day.popitem()
    print(day)
    

    Output:

     
    {'monday': 1, 'tuesday': 2, 'wednesday': 3, 'thursday': 4}
    

    Here,
    Last item in dictionary is friday. So, it has been removed from dictionary using popitem() method.

  3. Using del keyword

    del keyword removes dictionary completely or a specific key of dictionary and its value. It raises a keyError if key is not in Dictionary. For example,

    Deleting Dictioanry Using del Keyword

    del deletes dictionary with given name. For example,

     
    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
    del day
    print(day)
    

    Output:

    NameError: name 'day' is not defined
    

    Since print() function is trying to print dictionary after it has been deleted, it throws an error.

    Delete Specific Key of Dictionary Using Del

    Specific Key of Dictionary can be deleted using del keyword. For example,

    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
    del day["wednesday"]
    print(day)
    

    Output:

    {'monday': 1, 'tuesday': 2, 'thursday': 4, 'friday': 5}
    
  4. Using clear() method

    clear() method clears all items of dictionary i.e. dictioanry becomes empty. For example,

     
    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
    day.clear()
    print(day)
    

    Output:

     
    {}
    

    Note : clear() method removes all items in the dictionary and the dictionary remains in memory.

Iterate Through Dictionary

In this section, we are going to see how we can iterate through dictionary by making

  1. Iterate through Keys
  2. Iterate through Values
  3. Iterate through Items
  1. Iterating Through Keys

    Using for loop, each key of dictionary can be accessed as shown below –

     
    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
    for key in day :
        print(key, end=" ")
    

    Output:

     
    monday tuesday wednesday thursday friday
    

    Keys of dictionary can also be accessed using keys() method of dictionary. For example,

     
    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
    for key in day.keys() :
        print(key, end=" ") 
    

    Output:

     
    monday tuesday wednesday thursday friday
    

    keys() method returns all keys of dictionary. Then, using for loop each key is accessed.

  2. Iterating through Values

     
    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5} 
    for value in day.values() :
        print(value, end=" ") 
    

    Output:

     
    1 2 3 4 5
    
  3. Iterating through Items

    items() returns all items present in dictionary. Then, using for loop, each item can be accessed and printed.
    For example,

    day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
    for item in day.items() :
        print(item, end=" ")
    

    Output:

    ('monday', 1) ('tuesday', 2) ('wednesday', 3) ('thursday', 4) ('friday', 5)
    

Copy One Dictionary to Another Dictionary

To copy all items containing in one dictionary to another, we will use the method copy() of Dictionaries. For example,

 
week = { }
day = { "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}
week = day.copy()
print(week)

Output:

 
{ "monday" : 1, "tuesday" : 2, "wednesday" : 3, "thursday" : 4, "friday" : 5}

Different Methods of Dictionary

Methods Descriptions
pop()
  1. Removes specified key and returns the corresponding value.
  2. If the key is not found, returns the default if given otherwise raises a keyError.
setdefault()
  1. Takes as arguments key and its default value.
  2. Inserts key with a value of default if key is not in dictionary.
  3. Returns the value for key if key is in the dictionary, else default.
popitem()
  1. Removes and returns a (key, value) pair as 2-tuples.
  2. Pairs are returned in LIFO (last-in, first-out) order.
  3. Raises KeyError if the dictionary is empty.
clear()
  1. Removes all items from dictionary and returns None.
  2. But the dictionary object still remains in memory.
get()
  1. Takes key and its default value as arguments.
  2. Returns the value for key if key is in the dictionary, else default.
values()
  1. Returns an object providing a view on values of dictionary.
  2. In explicit way, this method returns an object that contains the list of values present in dictionary.
  3. In a simpler way values () method returns all values in the dictionary as sequence (in the form of list).
keys()
  1. Returns an object providing a view on keys of dictionary.
  2. In another way, this method returns an object that contains the list of keys present in dictionary.
  3. In a simpler way, keys() method returns all keys in the dictionary as sequence (in the form of list).
items()
  1. Returns an object providing a view on items of dictionary.
  2. Returns all the items in the dictionary as a sequence (in the form of list containing a tuple (key, value)).
copy()
  1. This method copy all items present in a dictionary to another.
update()
  1. This method takes a dictionary as argument and adds its items at the end of another dictionary.

Others functions working with Dictionaries

Function Description
sorted() Returns a list that contain the keys present in the dictionary.
len() Returns the length of dictionary or the number of item in the dictionary.
max() Returns the largest string if keys are string. It returns the maximum of keys if keys are tuple of integers.
min() Returns the smallest string if keys are string. It returns the minimum of keys if keys are tuple of integers.
all() This function returns True if all keys in dictionary are true or if the dictionary is empty.
any() This returns True if any key of the dictionary is true. It returns False if dictionary is empty
cmp() Takes two dictionaries as arguments and compares keys of each dictionary.

Nested Dictionary in Python

Previously we learnt about Dictionaries in Python. Now, we are going to converse around Nested Dictionary in Python.

What is Nested Dictionary in Python ?

In a simpler way, Nested Dictionary is a dictionary that contains another Dictionaries.

So like Dictionaries, Nested Dictionaries are mutable and unordered collections containing keys and their corresponding values.

Creating Nested Dictionary

As we say above, to create a Dictionary or Nested Dictionary in Python we can use curly bracket or dict() constructor or dictionary comprehension. But here for going quickly we will use the first way : Curly bracket.

 
books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
print(books) 

Output:

 
{1: {'name': 'The Adventures of Tintin', 'autor': 'Hergé'}, 2: {'name': 'Harry Potter', 'autor': 'Rowling'}}

Here,
We created a nested dictionary books using curly bracket. Similarly, you can use other ways of creating dictionary for nested dictionary.

Get Length of Nested Dictionary

To get the length of nested dictionary, we will use the Python internal function – len().This method will return the number of item or the number of keys contained in nested dictionary.

For example,

 
books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
print(len(books)) 

Output:

 
2

Here, total number of keys present in books dictionary is 2. Hence, len() returns 2.

Get Type of Nested Dictionary in Python

The Python internal function called type() will help us to know the type of a nested dictionary object. For example,

 
books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
print(type(books)) 

Output:

 
class 'dict'

Get Items Nested Dictionary in Python

Here, the only way to get item present in nested Dictionary like we want is to make an iteration through nested dictionary. For example,

 
books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
for key in books :
print(key, " : ", books[key]) 

Output:

 
1 : {'name': 'The Adventures of Tintin', 'autor': 'Hergé'}
2 : {'name': 'Harry Potter', 'autor': 'Rowling'}

We got items present in nested dictionary using for loop iteration.

Get Keys of Nested Dictionary in Python

Keys of nested dictionary can be found –

  1. Using Loop Method
  2. Using keys() Method
  1. Using Loop Method

    Using for loop, we can access keys of nested dictionary in python. Then, we print it using print() method. For example,

     
    books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
    for key in books :
         print(key, end=" ") 
    

    Output:

     
    1 2
    
  2. Using keys() method

    Using keys() method, we get all keys of nested dictionary in python. Then, we print it’s returned values. For example,

     
    books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
    print(books.keys())
    

    Output:

     
    dict_keys([1, 2])
    

    We will convert now this output into list object.

     
    books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
    print(list(books.keys())) 
    

    Output:

     
    [1, 2] 
    

Get Values of Nested Dictionary in Python

To get values of all keys present in the nested dictionary in python, we use values() method of dictionary.

 
books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
print(books.values())

Output:

 
dict_values([{'name': 'The Adventures of Tintin', 'autor': 'Hergé'}, {'name': 'Harry Potter', 'autor': 'Rowling'}])

Now, we can convert this output into list object.

 
books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
print(list(books.values()))

Output:

 
[{'name': 'The Adventures of Tintin', 'autor': 'Hergé'}, {'name': 'Harry Potter', 'autor': 'Rowling'}] 

Get Items of Nested Dictionary in Python

To get all items contain in nested dictionary, we use dictionary method called items(). For example,

 
books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
print(books.items()) 

Output:

 
dict_items([(1, {'name': 'The Adventures of Tintin', 'autor': 'Hergé'}), (2, {'name': 'Harry Potter', 'autor': 'Rowling'})]) 

Let’s convert this output into a list object.

 
books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
print(list(books.items()))

Output:

 
[(1, {'name': 'The Adventures of Tintin', 'autor': 'Hergé'}), (2, {'name': 'Harry Potter', 'autor': 'Rowling'})]

Checking if any Key Exist or Not

To check if any key is present in python nested dictionary or not, we can use in and not in operators. They will help us to verify if key exists or not in nested dictionary. They return True if condition is verified and False else.

  1. Using in Operator in Nested Dictionary

    It’s similar as simple dictionary in python. For example,

     
    books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
    print(1 in books)
    

    Output:

     
    True
    

    Let’s take another example,

     
    books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
    print(4 in books)
    

    Output:

     
    False
    
  2. Using not in Operator in Nested Dictionary

    It similar as not in operator in simple dictionary. For example,

     
    books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
    print(1 not in books)
    

    Output:

     
    False
    

    Let’s take another example,

     
    books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
    print(4 not in books)
    

    Output:

     
    True 
    

Add Item in Nested Dictionary in Python

Here, we can add item in Nested Dictionary by using square brackets [ ] or index syntax. For example,

 
books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
books[3] = {"name" :"The Hobbit", "autor" : "Tolkien" }
print(books) 

Output:

{1: {'name': 'The Adventures of Tintin', 'autor': 'Hergé'}, 2: {'name': 'Harry Potter', 'autor': 'Rowling'}, 3: {'name': 'The Hobbit', 'autor': 'Tolkien'}}

Note : When we want to add item to a dictionary or nested dictionary, the key of item must not exists in the dictionary or nested dictionary otherwise the value of item will be updated.

Update Item in Nested Dictionary in Python

To update item in nested dictionary, we can also use square brackets or index [ ] like previously. The difference between adding item and updating item is that with adding item the key must be a new key whereas with updating item the key must be existing key. For example,

 
books = { 1 : {"name" : "The Adventures of Tintin", "autor" : "Hergé"}, 2 : {"name" : "Harry Potter", "autor" : "Rowling"} }
books[1] = {"name" :"The Stranger", "autor" : "Albert Camus" } 
print(books) 

Output:

 
 {'name': 'The Stranger', 'autor': 'Albert Camus'}, 2: {'name': 'Harry Potter', 'autor': 'Rowling'}} 

Note : If the key not exists in dictionary or nested dictionary, the item (key : value) will be add the dictionary or nested dictionary.

Multiples Choices Questions on Dictionary and Nested Dictionary in Python

1. What will be the output of this Python code ?

 
fruits = { "mango" : 2, "banana" : 5, "pineapple" : 3, "orange" : 10} 
print(fruits.items())
 

a.) SyntaxError
b.) dict_items([(‘mango’, 2), (‘banana’, 5), (‘pineapple’, 3), (‘orange’, 10)])
c.) dict_items([(2, ‘mango’), (5, ‘banana’), (3, ‘pineapple’), (10, ‘orange’)])
d.) dict_items([2, 5, 3, 10])

2. Choose the correct output between these.

 
fruits = { "mango" : 2, "banana" : 5, "pineapple" : 3, "orange" : 10} 
for fruit in fruits :
    print(fruit, end = " ")

a.) mango banana pineapple orange
b.) 2 5 3 10
c.) “mango” 2 “banana” 5 “pineapple” 3 “orange” 10
d.) Error, it should be : for fruit in fruits.values()

3. What will be the output of this Python code ?

 
fruits = { "mango" : 2, "banana" : 5, "pineapple" : 3, "orange" : 10} 
print(fruits.pop("apple"))
 

a.) 2
b.) 10
c.) KeyError
d.) None of the above

4. Which of the following statement is wrong about dictionary keys ?
a.) Keys must be list object.
b.) Keys must be immutable.
c.) Keys must be integers.
d.) More than one key is not allowed.

5. What will be the output of this Python code ?

 
fruits = { "mango" : 2, "banana" : 5, "pineapple" : 3, "orange" : 10} 
fruits.clear()
print(fruits)
 

a.) None
b.) {None : None, None : None, None : None, None : None}
c.) { }
d.) {“mango” : None, “banana” : None, “pineapple” : None, “orange” : None}

6. What will be the output of this Python code ?

 
fruits = { "mango" : 2, "banana" : 5, "pineapple" : 3, "orange" : 10}
my_fruit = fruits.copy()
print(my_fruit)
 

a.) a. {“mango” : 2, “banana” : 5, “pineapple” : 3, “orange” : 10}
b.) None
c.) Error, copy method doesn’t exist for dictionaries
d.) None of the above.

7. What will be the output of the following Python code ?

 
fruits = { "mango" : 2, "banana" : 5, "pineapple" : 3, "orange" : 10} 
fruits.setdefault("apple", 8)
print(fruits)
 

a.) Error
b.) None
c.) { “mango” : 2, “banana” : 5, “pineapple” : 3, “orange” : 10, “apple” : 8}
d.) KeyError

8. What will be the output of the following Python code ?

 
fruits = { "mango" : 2, "banana" : 5, "pineapple" : 3, "orange" : 10} 
print(fruits.setdefault("orange"))
 

a.) No method called setdefault exists for dictionary.
b.) 10
c.) { “mango” : 2, “banana” : 5, “pineapple” : 3, “orange” : 10}
d.) KeyError

9. Which of the following statement is declaration of the dictionary.
a.) dict([ [1, 8], [“A”, 10] ])
b.) { 1, “mango”, 2, “orange”, 3, “apple” }
c.) { }
d.) None of the above

10. What will be the output of this Python code ?

 
fruits = { "mango" : 2, "banana" : 5, "pineapple" : 3, "orange" : 10} 
for i, j in fruits.items() :
    print(i, j, end= " ")
 

a.) mango 2 banana 5 pineapple 3 orange 10
b.) (“mango” , 2), (“banana”, 5), (“pineapple”, 3), (“orange”, 10)
c.) Error
d.) Dictionary don’t have method called items()

11. What will be the output of this Python code ?

 
fruits = { "mango" : 2, "banana" : 5, "pineapple" : 3, "orange" : 10} 
my_fruit = { "apple" : 12, "avocado" : 15}
fruits.update(my_fruit)
print(fruits)
 

a.) No method update () for dictionaries in Python.
b.) { “mango” : 2, “banana” : 5, “pineapple” : 3, “orange” : 10}
c.) {“mango” : 2, “banana” : 5, “pineapple” : 3, “orange” : 10, “apple” : 12, “avocado” : 15}
d.) KeyError

12. What is correct output between these ?

 
fruits = { "mango" : 2, "banana" : 5, "pineapple" : 3, "orange" : 10} 
print(fruits.get("apple", 14))
 

a.) Error, invalid syntax
b.) 14
c.) mango
d.) None of the above

13. Check the correct output

 
 fruits = { "mango" : 2, "banana" : 5, "pineapple" : 3, "orange" : 10} 
 print(fruits.get("mango", 14))
 

a.) No get() method for dictionaries in Python.
b.) Error, invalid syntax.
c.) 2
d.) None of the above.

14. What will be the output of this Python code.

 
fruits = { "mango" : 2, "banana" : 5, "pineapple" : 3, "orange" : 10} 
del fruits["apple"]
print(fruits) 
 

a.) No method del for dictionaries
b.) KeyError
c.) None
d.) mango

15. What will be the output of this Python code ?

 
fruits = { "mango" : 2, "banana" : 5, "pineapple" : 3, "orange" : 10} 
fruits.pop("mango")
print(fruits)
 

a.) Error, syntax error for pop method.
b.) { “mango” : 2, “banana” : 5, “pineapple” : 3, “orange” : 10}
c.) {“banana” : 5, “pineapple” : 3, “orange” : 10}
d.) None of the above.

That’s end of tutorial on python dictionary and nested dictionary. Learn more at official documentation

Leave a Reply

We are actively looking for Paid Content Writer. Email us at tutorialwing@gmail.com if you are interested.