20 Python dictionary theoretical interview questions

Interview Question

1. What is Python dictionary?

Python Dictionary is an in-built collection data type that does not contain duplicates generally known as an associative array. It is an ordered collection( As of Python version 3.7, dictionaries are ordered. But in Python version 3.6 and earlier, dictionaries are unordered).

A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value. Dictionary is listed in curly brackets, inside these curly brackets, keys and values are declared. Each key is separated from its value by a colon (:), while commas separating each element.

Dictionary contains unique keys, but values can be duplicated. We can’t use the index to access the dictionary element else use the keys because Dictionary is indexed by keys.

2. What are different Properties of Python Dictionary?

  • Dictionaries are mutable, which means that we can edit, add or remove items after the dictionary has been created. Dictionaries are dynamic in nature and they can grow in size or shrink in size at run time as per our program need.
  • Dictionaries can be nested into each other, which means a dictionary can contain another dictionary.
  • Dictionary elements can be accessed by using keys.
  • Dictionaries hold the data as key-value pairs. For each key, we have a value that makes the dictionaries very easy to access.
  • Dictionary keys do not allow polymorphism means it allows only unique keys. Dictionaries do not allow two items with the same key. All key has to be unique.
  • Dictionary keys are case sensitive, which means you can use the same key with a different case and they will be treated as different keys. For example, name and NAME are two different keys.
  • Dictionaries are unordered and their data elements are not accessible in a defined order, this is the reason we can not use indexing to access dictionary elements. We need to use keys to access dictionary elements.
  • The data elements in the dictionary can be of any data type. You can have data of any basic or user-defined data types in dictionary-like strings, int, boolean, lists, etc.

3. How to create a Python dictionary?

In Python two ways to create Dictionary in Python

  • Using curly braces{ }
  • Using dict() constructor

4. What is dict() in Python dictionary?

The dict() is a constructor to create a dictionary. It does not return anything.

Syntax

dict(keyword_agrument*)

Keyword_argument*: Any number of (key:value,……..key:valueN) arguments can be passed separated by comma.

5. How to use curly braces({}) to Create Dictionary?

In this example we are using the curly braces {} from to create a Python dictionary with integer and string keys

Create Dictionary with integer keys

#create a dictionary with data integer keys

first_dict = {1:'Dog', 2:'cat',3:'rat'}

print("dictionary with integer key:\n ")

print(first_dict)



Output

dictionary with data integer key :
 
{1: 'Dog', 2: 'cat', 3: 'rat'}




Create Dictionary with string keys

#create a dictionary with string as key type

first_dict = {'name':'Dog', 'pet':'cat','animal':'rat'}

print("dictionary with string as key type:\n ")

print(first_dict)

output

dictionary with string as key type:
 
{'name': 'Dog', 'pet': 'cat', 'animal': 'rat'}

6. How to Create Dictionary using dict() from a list of tuples?

In this example we are using the dict() constructor to create a Python dictionary from list of tuples

#dictionary with data

first_dict =  dict({1: 'apple', 2: 'orange', 3:'kiwi'})

print("dictionary with data: ")

print(first_dict)


#dictionary from a list of tuples

first_dict = dict([(1, 'apple'), (2, 'orange'),(3,'kiwi')])

print("dictionary from a list of tuples: ")

print(first_dict)

Output

Dictionary with data: 

{1: 'apple', 2: 'orange', 3: 'kiwi'}


dictionary from list of tuples: 

{1: 'apple', 2: 'orange', 3: 'kiwi'}

7. How to add/append item in Python Dictionary?

The Items in the python dictionary can be added/append key-values pair using these ways.

There are two ways to append value to a python dictionary.

  • Using subscript notation: add new key-value pair to Python dictionary
  • Using Update() Method : Dictionary update() method update key’s value if already exits else add new key-value pair.

For details :

Add new key-value pair Using subscript notation

In this, we have an empty dictionary and we are adding a new key-value pair using the subscript notation([]).In this ‘math’ is key and the value is 100

dict_sub = {}
dict_sub['math'] = 100
print('after adding value to dictionary =',dict_sub)

Now we have new key ‘math‘ with value 100 in dictionary

Output

after adding value to dictionary = {'math': 100}

Add a key-value pair to a dictionary using update() Method

dict_sub = {'math':100,'Eng':100,'Chem':98}

#adding key-value pair using update() method

dict_sub.update({'Phy':98})

print('after adding value to dictionary =\n',dict_sub)

Output

after adding value to dictionary =
 {'math': 100, 'Eng': 100, 'Chem': 98, 'Phy': 98}

8. What is Python dictionary update() method?

The update() is an inbuilt python dictionary method that takes a sequence as an argument, The sequence can pair of a key-value pair, a dictionary, iterable(tuple, list of tuples). It allows us to add a new key-value pair if does not exist in the dictionary,else update the value of the existing key.

Syntax

dict.update(iterable)

Parameter

Iterable: It can be a pair of key-value, dictionary or iterable of key-value pair (tuple, list of tuples) as an argument

Return Value : none

after adding value to dictionary =
 {'math': 100, 'Eng': 100, 'Chem': 98, 'Phy': 98}

9. How to get all keys of dictionary?

To get all keys of the Python dictionary inbuilt keys() method is used.Let understand with an example

first_dict =  dict({1: 'apple', 2: 'orange', 3:'kiwi'})



print('get dictionary keys :',first_dict.keys())

Output

get dictionary keys : dict_keys([1, 2, 3])

10.How to get all values of Python dictionary?

To get all values of the python dictionary inbuilt values() method is used.Let understand with an example

first_dict =  dict({1: 'apple', 2: 'orange', 3:'kiwi'})



print('get dictionary values :',first_dict.values())

Output

get dictionary values : dict_values(['apple', 'orange', 'kiwi'])

11. How to get Python dictionary all key-values pair?

We can use Python dictionary inbuilt items() method to get all key-value pairs of a dictionary.

first_dict =  dict({1: 'apple', 2: 'orange', 3:'kiwi'})



print('get dictionary keys-values :\n',first_dict.items())

Output

get dictionary keys-values :
 dict_items([(1, 'apple'), (2, 'orange'), (3, 'kiwi')])

12. How to loop over python dictionary?

For loop : To access value by key of Python dictionary

first_dict =  dict({1: 'apple', 2: 'orange', 3:'kiwi'})

print("Keys and Values: ")
for key in first_dict :
   print(key, first_dict[key])

Output

Keys and Values: 
1 apple
2 orange
3 kiwi

List comprehension : to access value by key of python dictionary

first_dict =  dict({1: 'apple', 2: 'orange', 3:'kiwi'})

print("Keys and Values: ")

print([(key, first_dict[key]) for key in first_dict])


Output

Keys and Values: 
[(1, 'apple'), (2, 'orange'), (3, 'kiwi')]

13. How to access items of Python dictionary?

  • To access an item of dictionary we can use the get() method
  • To access an item of the dictionary we can access a key name.
first_dict =  dict({1: 'apple', 2: 'orange', 3:'kiwi'})

key  = 3


print('Find values of given key :\n',first_dict[key])




print('FInd values of given key using get() method :\n',first_dict.get(key))

Output

FInd values of given key :
 kiwi
FInd values of given key using get() method :
 kiwi

14. How to update a Python Dictionary?

To update a Python dictionary there are two ways:

  • Using the key name
  • Using the dictionary update() method

Using key name

first_dict =  dict({1: 'apple', 2: 'orange', 3:'kiwi'})


first_dict[3] = 'apple'


print('updated dictionary using key name :\n',first_dict)

Output

updated dictionary using key name :
 {1: 'apple', 2: 'orange', 3: 'apple'}

Update dictionary using update() method

The update() method updates the Python dictionary with the items pass as arguments.

The is mandatory argument must be a dictionary, or an iterable object with key: value pairs.

first_dict =  dict({1: 'apple', 2: 'orange', 3:'kiwi'})



first_dict.update({20:'palm'})


print('updated dictionary using update() method :\n',first_dict)

Output

updated dictionary using update() method :
 {1: 'apple', 2: 'orange', 3: 'kiwi', 20: 'palm'}

15. How to remove item from Python dictionary?

There are many ways to delete elements from Python Dictionary

  • pop(): It removes the with the specified key name.
  • popitem(): It deletes the last inserted item.
  • del: It deletes the item with the specified key name or it deletes the dictionary completely if the key name is not passed
  • clear() : It empties the dictionary

Remove item Using Dictionary Pop() Method

dict_sub = {'math':100,'Eng':100,'Chem':98,'Sci':99,'Phy':100}



dict_sub.pop('Phy')

print('dictionary after pop item using pop() method =\n',dict_sub)


#output :
dictionary after pop item using pop() method =
 {'math': 100, 'Eng': 100, 'Chem': 98, 'Sci': 99}

Remove item Using Dictionary Using popitem() Method

dict_sub = {'math':100,'Eng':100,'Chem':98,'Sci':99,'Phy':100}



dict_sub.popitem()

print('dictionary after pop item using popitem() method =\n',dict_sub)

#Output :
dictionary after pop item using popitem() method =
 {'math': 100, 'Eng': 100, 'Chem': 98, 'Sci': 99}

Remove item Using Dictionary Using del Method

dict_sub = {'math':100,'Eng':100,'Chem':98,'Sci':99,'Phy':100}



del dict_sub['Sci']

print('dictionary after pop item using del method =\n',dict_sub)

#output :
dictionary after pop item using del method =
 {'math': 100, 'Eng': 100, 'Chem': 98, 'Phy': 100}

Remove item Using Dictionary Using del Method

dict_sub = {'math':100,'Eng':100,'Chem':98,'Sci':99,'Phy':100}


print('dictionary after pop item using del method =\n',dict_sub.clear())

#output :
dictionary after pop item using del method = none

16. What is dictionary comprehension?

Dictionary Comprehension is a smart and simple way to create a new dictionary from python iterable.

The dictionary Comprehension contains the form of an expression pair ({key: value} followed by for loop inside curly braces

Syntax for dictionary comprehension

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

Creating a new dictionary from iterable(list)

keys_lst = ['at','an','am','as']
values_lst = [11,12,13,14,15]

dict_sub = { key:val for (key,val) in zip(keys_lst, values_lst)}  

print('dictionary from lsit iterable:\n',dict_sub)


#output
dictionary from lsit iterable:
 {'at': 11, 'an': 12, 'am': 13, 'as': 14}

17.How to use dictionary comprehension with condition?

We can add single or multiple condition in dictionary comprehension.Using the python if statement let us understand how to achieve this using example.

Single condition with dictionary comprehension

my_dict = {'at': 1, 'as': 20, 'am': 30, '15': 4, 'e': 5}

dict_output = {key:val for (key,val) in my_dict.items() if val%2==0}

print(dict_output)

#output:

{'as': 20, 'am': 30, '15': 4}

multiple condition with dictionary comprehension

my_dict = {'at': 12, 'as': 20, 'am': 30, 'tat': 18, 'rat': 16}

dict_output = {key:val for (key,val) in my_dict.items() if val>12 if val%2 == 0}

print(dict_output)

#output
{'as': 20, 'am': 30, 'tat': 18, 'rat': 16}

18 .What is Python dictionary copy() method?

The Python dictionary copy() method return a copy of existing dictionary.

original_dict = {'at': 12, 'as': 20, 'am': 30, 'rat': 16}

copy_dict = original_dict.copy()

print(copy_dict)

#output
{'at': 12, 'as': 20, 'am': 30, 'rat': 16}

19. What is Python dictionary setdefault() method?

The setdefault() Python dictionary method returns the value of a key( when the key is in a dictionary) if the key not in the dictionary then the setdefault() method inserts the key with a value.

Syntax

dict.setdefault(key,defaultvalue) 

setdefault() Parameters
setdefault() takes two parameters:

  • key – The key we are looking at in the dictionary
  • default_value (optional) -if the key is not in the dictionary and if default_value is provided then the key with default_value is inserted into the dictionary. If default_value not provided then it will be None.
original_dict = {'num': 12, 'as': 20, 'am': 30, 'rat': 16}

# num key exist in dictionary 
value = original_dict.setdefault('num')

print('value of num key:',value)


#age key does not exist in the dictionary so insert with a default value

age = original_dict.setdefault('age',20)

print('value of age key:',age)

print('dict :',original_dict)




#Output
value of num key: 12

value of age key: 20
dict : {'num': 12, 'as': 20, 'am': 30, 'rat': 16, 'age': 20}


20.What of following statement can create dictionary?

As mention above python dictionary can be created using {} brackets.So here we are creating dictionary using the {}.

a) dict = {}
b) dict = (12:"banana", 13:"food")
c) dict = {"C#":10, "py":45}
d) dict = {30:"apple", 45:"orange"}

Output

a,b,d

21. What will be output of this program?

dict = {}
#dict = (12:"banana", 13:"food")
dict = {"C#":10, "py":25}
dict = {30:"apple", 45:"orange"}

print(dict)

Output

{30: 'apple', 45: 'orange'}