Python: 25 Dictionary Programming interview questions and answers

In this post, we are going to explore most asked 25 Dictionary Programming interview questions and answers

1. What will be output of following program

dict = {(3,4,8):4,(5,6,9):3}
print('output:',dict[5,6,9])

Output

output: 3

Must Read :

2. Get keys[“name”, “age”] from dictionary and create new dictionary

keys values we have to get, We are using the dictionary comprehension with IN operator to find the keys: [“name”, “age”] we are looking in the dictionary

animaldict = {
  "name": "Dog",
  "age":5,
  "Weight": 4,
  "Country": "US",
  "City":"California"
  
}


outDict = {key: animaldict[key] for key in  ["name", "age"]}
print(outDict)

Output

{'name': 'Dog', 'age': 5}

Related Post

3. Program to delete set of keys from Dictionary

keys to delete : [“name”, “age”]

animaldict = {
  "name": "Dog",
  "age":5,
  "Weight": 4,
  "Country": "US",
  "City":"California"
  
}


outDict = {key: animaldict[key] for key in animaldict.keys()-  ["name", "age"]}
print(outDict)

Output

{'City': 'California', 'Weight': 4, 'Country': 'US'}

4. What will the output of following Program

dictlang = {'c#': 6, 'GO': 89, 'Python': 4,'Rust':10}

for _ in sorted(dictlang):
    print (dictlang[_])

Output

89
4
10
6

5. Guess output of this Program

Here, we are checking copying one dictionary to another dictionary has the same ID. It will return true or false.

dictlang = {'c#': 6, 'GO': 89, 'Python': 4,'Rust':10}

cpydict = dictlang.copy()
print(id(cpydict) == id(dictlang))

Output

False

6. How to change the name of key in dictionary.

Here we have to change the key “name “ to “Animalname” in nested dictionary.

animaldict = {
  "name": "Dog",
  "age":5,
  "Weight": 4,
  "Country": "US",
  "City":"California"
  
}

animaldict['Animalname'] = animaldict.pop('name')

print(animaldict)

Output

{'age': 5, 'Weight': 4, 'Country': 'US', 'City': 'California', 'Animalname': 'Dog'}

7.What will the output of following program

dictlang = {'c#': 6, 'GO': 89, 'Python': 4,'Rust':10}

print (dictlang['C#','GO'])

Output

KeyError: ('C#', 'GO')

8. How to change the value of any key in nested dictionary

here,we are changing the age of animal “cat” in nested “Animal 1” dictionary.

animaldict = {
  "animal":{
  "name": "Dog",
  "age":5,
  
 
  },
    "animal1":{
  "name": "Cat",
  "age":2,

 
  },
    "animal2":{
  "name": "Rabbit",
  "age":1,
 
 
  },

  
}

animaldict["animal1"]['age'] = 5

print(animaldict)

Output

{'animal': {'name': 'Dog', 'age': 5}, 
'animal1': {'name': 'Cat', 'age': 5}, 
'animal2': {'name': 'Rabbit', 'age': 1}}

9.How to delete a key from Dictionary

fruitsDict = {
  'Apple': 100,
  'Orange': 200,
  'Banana': 400,
  'pomegranate':600
}
if 'Apple' in fruitsDict: 
    del fruitsDict['Apple']

print('Dict after deleting key =',fruitsDict)

Output

Dict after deleting key = {'Orange': 200, 'Banana': 400, 'pomegranate': 600}

10. What will be the output of following program

fruitsDict = {
  'Apple': 100,
  'Orange': 200,
  'Banana': 400,
  'pomegranate':600
}

fruitsDict = {}
print('Dictionary length =',len(fruitsDict))

Output

Dictionary length = 0

11. How to get min and max keys corresponding to min and max value in Dictionary

fruitsDict = {
  'Apple': 100,
  'Orange': 200,
  'Banana': 400,
  'pomegranate':600
}

print('min value key = ',min(fruitsDict, key=fruitsDict.get))
print('max value key =',max(fruitsDict,key=fruitsDict.get))

Output

min value key =  Apple
max value key = pomegranate

12. How to concatenate multiple dictionary in one

Using for-loop and update() we can concatenate multiple dictionary in one

Fruit = {'Apple': 100, 'banana': 5}

Subject =  {'Math': 100, 'English': 98} 

animal =  {'name': 'Rabbit', 'age': 1}

conacte_Dict =  {}

for dict in (Fruit, Subject, animal): conacte_Dict.update(dict)

print(conacte_Dict)


Output

{'Apple': 100, 'banana': 5, 'Math': 100, 'English': 98, 'name': 'Rabbit', 'age': 1}

13.How to sum all elements of Dictionary

Using the sum() method we can sum the Dictionaries elements.

Fruit = {'Apple': 100, 'banana': 5,'orange':45,'Guava':60}

print('sum of dict elements = ',sum(Fruit.values()))

Output

sum of dict elements =  210

14.How to multiply all elements of dictionary

FruitDict = {'Apple': 10, 'banana': 5,'orange':4,'Guava':6}
mutiply_res = 1
for key in FruitDict:    
    mutiply_res = mutiply_res * FruitDict[key]

print('mutiplication of dict elements = ',mutiply_res)

Output

mutiplication of dict elements =  1200

15.How to sort a dictionary by key

FruitDict = {'Apple': 10, 'Banana': 5,'Orange':4,'Guava':6}

print('sorted dictionary = ')
for key in sorted(FruitDict):
    print("%s: %s" % (key, FruitDict[key]))

Output

sorted dictionary = 
Apple: 10
Banana: 5
Guava: 6
Orange: 4

16. How do we find highest 2 values in a dictionary

from heapq import nlargest
FruitDict = {'Apple': 600, 'Banana': 515,'Orange':214,'Guava':1116}  
two_highest_values = nlargest(2, FruitDict, key=FruitDict.get)
print(two_highest_values) 

Output

['Guava', 'Apple']

17.How to convert a string in dictionary

from collections import defaultdict, Counter

mystring = 'DictExample' 
string_dict = {}

for word in mystring:
    string_dict[word] = string_dict.get(word, 0) + 1
print(string_dict)

Output

{'D': 1, 'i': 1, 'c': 1, 't': 1, 'E': 1, 'x': 1, 'a': 1, 'm': 1, 'p': 1, 'l': 1, 'e': 1}

18.How to print Dictionary as table

Dict_tab = {'Students':['Rack','Jack','John'],'Fruit':['Apple','Banana','Orange'],'Subject':['Phy','Math','English']}

for row in zip(*([key] + (value) for key, value in sorted(Dict_tab.items()))):
    print(*row)

Output

Fruit Students Subject
Apple Rack Phy
Banana Jack Math
Orange John English

19. How to remove space between dictionary keys.

myDict = {'Fr   uit':['Apple','Banana','Orange'],'Sub   ject':['Phy','Math','English']}

myDict = {i.translate({32: None}): j for i, j in myDict.items()}

print("dict after remove space = ",myDict)

Output

dict after removing key space =  {'Fruit': ['Apple', 'Banana', 'Orange'], 'Subject': ['Phy', 'Math', 'English']}

20. How to remove no value items from Dictionary.

mutidict = {'lang': 'C#', 'Fruit': 'Apple', 'Subj':None,'Animal':None}


OutDict = {key:value for (key, value) in mutidict.items() if value is not None}
print(OutDict)

Output

{'lang': 'C#', 'Fruit': 'Apple'}

21.How to filter dictionary based on value.

empdict = {'Jack': 12000, 'Max': 20000, 'Hack':25000,'Nack':80000}


filterEmpDict = {key:value for (key, value) in empdict.items() if value <= 80000}
print('Fillter dictionary = ',filterEmpDict)

Output

Fillter dictionary =  {'Jack': 12000, 'Max': 20000, 'Hack': 25000, 'Nack': 80000}

22.How to convert nested tuples into custom key dictionary

empdict = [(('Salary','of','Racx'), 12000), (('Salary','of','Tax'),80000)]

output = {' '.join(key): val for key, val in empdict} 

print("Custom key dictionary : " , output) 

Output

The computed Dictionary :  {'Salary of Racx': 12000, 'Salary of Tax': 80000}

23.How to check number of keys have same value.

empdict = {'Racx': 12000, 'Max':80000,'Stack':80000,'John':80000,}


valuetofind = 80000

count = sum(val == valuetofind for val in empdict.values())  
 
print("number of keys have same value : " ,count) 

Output

number of keys have same value :  3

24.How to convert dictionary object into string

personDict = { "Name" : "Simulen", 
          "City" : "CA", 
          "Country" : "USA"} 

print ('Type before conversion = ',type(personDict)) 


dicttoString = str(personDict) 

print ("\ntype after conversion = ", type(dicttoString)) 
print ("\ndict object to string = ", dicttoString) 

Output

Type before conversion =  <class 'dict'>

type after conversion =  <class 'str'>

dict object to string =  {'Name': 'Simulen', 'City': 'CA', 'Country': 'USA'}

25.Program to add multiple keys into dictionary

personDict = {'person':{ "Name" : "Simulen", 
          "City" : "CA", 
          "Country" : "USA"}}

 


personDict['person']['Company'] = 'Morgan stanely'
  
 
print("Dictionary after adding key =\n" ,personDict) 

Output

Dictionary after adding key =
 {'person': {'Name': 'Simulen', 'City': 'CA', 'Country': 'USA', 'Company': 'Morgan stanely'}}