4️⃣ Dictionary
Dictionary is the data structure of python which stores the data in the form of key-value pairs.
The dictionary always contains unique keys.
Values in dictionary can be duplicate.
Each key-value pair is comma separted and enclosed in curly braces { } in dictionary.
Dictionary datatype variable will be of type <class ‘dict’>
Sequence or order of dictionary keys always maintained.
💻 Example:
1 2 | roll_number = { 1:'Shubham', 2:'Sam', 3:'Raj' }
print(type(roll_number))
|
✅ Output:
<class 'dict'>
Value for particular key from dictionary can be found by passing the key name to dictionary .
💻 Example:
1 2 | print(roll_number[3])
print(roll_number[2])
|
✅ Output:
Raj
Sam
If you try to get the value for key which does not present in dictionary, it will provide KeyError.
💻 Example:
1 | print(roll_number['sid'])
|
✅ Output:
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
roll_num['sid']
KeyError: 'sid'
We can update the current dictionary with new key-value pair as follows:
💻 Example:
1 2 3 | roll_number[4] = 'Ram'
roll_number[5] = 'Samy'
print(roll_number)
|
✅ Output:
{ 1:'Shubham', 2:'Sam', 3:'Raj', 4:'Ram', 5:'Samy' }
How to define blank dictionary ? We can define empty dictionaries using two ways
using builtin function: dict()
using symbol: {}
💻 Example:
1 2 3 4 | mydict = {}
mydict2 = dict()
print('The value of mydict:', mydict)
print('The value of mydict2:', mydict2)
|
✅ Output:
The value of mydict: {}
The value of mydict2: {}
Dictionary can contain keys and values data of different datatypes.
💻 Example:
1 2 3 4 5 6 7 8 9 | school_info = {
'name': 'International',
'student': 2000,
1: 'Div-A',
2: 'Div-B',
'Gov_Approved': True,
'Address':'Bakers Road, New York',
'Division':[1, 2]
}
|
Dictionary Methods
1) .keys(): We can get only keys present in dictionary by .keys() method.
💻 Example:
1 2 | dictionary = { 'one':1, 'two':2, 'three':3 }
print(dictionary.keys())
|
✅ Output:
dict_keys{['one','two','three']}
2) .values(): Similarly we can get the values present in dictionary using .values() method on dictionary.
💻 Example:
1 | print(dictionary.values())
|
✅ Output:
dict_values{[1,2,3]}
3) .items(): We can use this method to get the key_value pairs in the from of tuples inside list.
💻 Example:
1 | print(dictionary.items())
|
✅ Output:
dict_items([('one', 1), ('two', 2), ('three', 3)])
4) .update(): We can use this method to update or merge existing dictionary with another dictionary.
💻 Example:
1 2 3 4 5 | mydict = {'one':1, 'two':2, 'three':3}
mydict2 = {'four':4, 'five':5}
# update first dictionary with second
mydict.update(mydict2)
print(mydict)
|
✅ Output:
{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
Trick: Using dict() method with zip() method: We can convert two lists in to dictionary where first list items are key and second list items are values. Provided both lists should have same length.
💻 Example:
1 2 3 4 5 | a = ['divA','divB','divC']
b = [50, 60, 95]
division_dict = dict(zip(a,b))
print(type(division_dict))
print(division_dict)
|
✅ Output:
<class'dict'>
{'divA':50, 'divB':60, 'divC':95}
Nested Dictionary
Nested dictionary contains dictionaries inside dictionary.
💻 Example:
1 2 3 4 5 6 | society = {
'wingA':{'flats':20, 'vehicles':33},
'wingB':{'flats':25, 'vehicles':55},
'wingC':{'flats':18, 'vehicles':37},
'wingD':{'flats':20, 'vehicles':44}
}
|
Lets find number of vehicles present in the C wing of society.
💻 Example:
1 | print(society['wingC']['vehicles'])
|
✅ Output:
37
Lets find number of flats present in the B wing of society.
💻 Example:
1 | print(society['wingB']['flats'])
|
✅ Output:
25
Dictionary Comprehension
Dictionary comprehension is used to get new dictionary with required transformation from existing dictionary.
It is similar to list comprehension.
Lets get the dictionary from current dictionary which will have the values as square of the current values.
💻 Example:
1 2 3 | numDict = {'one':1,'two':2,'three':3,'four':4}
squareDict = {k:v**2 for (k,v) in numDict.items()}
print(squareDict)
|
✅ Output:
{'one':1,'two':4,'three':9,'four':16}
Here are the quick notes on above topic:
Be prepared with below questions prior to your interview !
Frequently asked Interview Questions
What is a python dictionary?
How to define a dictionary in Python?
What is the difference between python dictionary and list?
How do you access values and keys in a dictionary?
What happens if you try to access a key that does not exist in a dictionary?
How do you add or update key-value pairs in a dictionary?
How can you remove a key-value pair from a dictionary?
Can a dictionary have duplicate keys?
How do you iterate over the key-value pairs in a dictionary?
Is a dictionary sequential or non-sequential datatype? Explain.