(1) What Is A Python Dictionary? How Does It Work?
- Python Dictionary objects are data types that are enclosed in curly braces ‘{}’ and have key and value pairs and each pair is separated by a comma.
- The dictionary is mapped. Meaning since it has key and value pair, a meaningful key can save a lot of trouble for coders, like using an address key to save all the addresses, an id key for all id’s and so on.
- Moreover, as of Python >3.6, dictionaries also preserve the order.
Example-1
student = {'Name':'Subrat',
'Subject':'Math',
'Mark':88}
print(student)
{'Name': 'Subrat', 'Subject': 'Math', 'Mark': 88}
(2) How To I Get Keys Of Dictionary?
- Dictionary comes with keys() method that provides a list of all the keys in the dictionary.
Example-1
student = {'Name':'Subrat',
'Subject':'Math',
'Mark':88}
student.keys()
dict_keys(['Name', 'Subject', 'Mark'])
(3) How To I Get Values Of Dictionary?
- values() method that provides a list of all the keys in the dictionary.
Example-1
student = {'Name':'Subrat',
'Subject':'Math',
'Mark':88}
student.values()
dict_values(['Subrat', 'Math', 88])
(4) How To Get Key And Value Pair Of A Dictionary?
- items() method that returns list consisting of key and value tuples.
Example-1
student = {'Name':'Subrat',
'Subject':'Math',
'Mark':88}
student.items()
dict_items([('Name', 'Subrat'), ('Subject', 'Math'), ('Mark', 88)])
(5) How Do I Check If Key Exists In A Dictionary?
- You can use if statement with in to check if the key exists.
Example-1
if 'Name' in student:
print(student['Name'])
Subrat
(6) Are Dictionaries Mutable?
- Yes,
- The Python dictionary is a mutable object. Meaning, we can change, add or remove key-value pairs after assigning.
Example-1
student = {'Name':'Subrat',
'Subject':'Math',
'Mark':88,
'Nationality':'Indian',
'Gender':'Male'}
student['Mark'] = 90
print(student)
{'Name': 'Subrat', 'Subject': 'Math', 'Mark': 90, 'Nationality': 'Indian', 'Gender': 'Male'}
(7) Is It Possible To Find The Length Of A Dictionary?
- Yes, len() can provide length for the dictionary too.
Example-1
student = {'Name':'Subrat',
'Subject':'Math',
'Mark':88,
'Nationality':'Indian',
'Gender':'Male'}
len(student)
5
(8) What’s The Difference Between list.pop() and dictionary.pop()
- The pop() method in the list REMOVE the last item in the list, however, the pop() method in the dictionary can remove a specified item.
- The dict.popitem() would be the equivalent of list.pop().
- FYI, if you want to clear the dictionary in one fell swoop use the clear() method.
Example-1
student = {'Name':'Subrat',
'Subject':'Math',
'Mark':88,
'Nationality':'Indian',
'Gender':'Male'}
popped = student.popitem()
print(popped)
print(student)
('Gender', 'Male')
{'Name': 'Subrat', 'Subject': 'Math', 'Mark': 88, 'Nationality': 'Indian'}
(9) How To Sort Dictionary Keys And Values.
- Dictionary items can be sorted by both keys and values.
Example-1: Sorting Based On Key
studemt_marks = {'Subrat':76,
'Subhada':98,
'Arpita':76,
'Abhispa':89}
new_dict = dict(sorted(studemt_marks.items()))
new_dict
{'Abhispa': 89, 'Arpita': 76, 'Subhada': 98, 'Subrat': 76}
Example-2: Sorting Based On Key -Reverse Order.
studemt_marks = {'Subrat':76,
'Subhada':98,
'Arpita':76,
'Abhispa':89}
new_dict = dict(sorted(studemt_marks.items(), reverse = True))
new_dict
{'Subrat': 76, 'Subhada': 98, 'Arpita': 76, 'Abhispa': 89}
Example-3: Sorting Based On Key – Dictionary Comprehension
studemt_marks = {'Subrat':76,
'Subhada':98,
'Arpita':76,
'Abhispa':89}
Keys = list(studemt_marks.keys())
Keys.sort()
new_dict = {key: studemt_marks[key] for key in Keys}
new_dict
{'Abhispa': 89, 'Arpita': 76, 'Subhada': 98, 'Subrat': 76}
Example-4: Sorting Based On Value
studemt_marks = {'Subrat':76,
'Subhada':98,
'Arpita':79,
'Abhispa':89}
sorted_dict = sorted([(value, key) for (key, value) in studemt_marks.items()])
sorted_dict
[(76, 'Subrat'), (79, 'Arpita'), (89, 'Abhispa'), (98, 'Subhada')]
Example-5: Sorting Based On Value: Reverse Order
studemt_marks = {'Subrat':76,
'Subhada':98,
'Arpita':79,
'Abhispa':89}
sorted_dict = sorted([(value, key) for (key, value) in studemt_marks.items()], reverse = True)
sorted_dict
[(98, 'Subhada'), (89, 'Abhispa'), (79, 'Arpita'), (76, 'Subrat')]
(10) How To Merge Two Dictionary.
- “|” operator is used to merge dictionaries.
Example-1
student = {'Name':'Subrat',
'Subject':'Math',
'Mark':88,
'Nationality':'Indian',
'Gender':'Male'
}
college = {
'College':'GIET',
'University':'BPUT',
}
student | college
{'Name': 'Subrat',
'Subject': 'Math',
'Mark': 88,
'Nationality': 'Indian',
'Gender': 'Male',
'College': 'GIET',
'University': 'BPUT'}
(11) How To Convert List To Dictionary
Example-1: Fixed Value
pets= ['dog','cat','guinea pig', 'parrot']
pets_owner ={animal:'Jackson' for animal in pets}
pets_owner
{'dog': 'Jackson',
'cat': 'Jackson',
'guinea pig': 'Jackson',
'parrot': 'Jackson'}
Example-2: Using For Loop
pets= ['dog','cat','guinea pig', 'parrot']
numbers = [2,4,10,2]
pet_number_dict={}
for animal,num in zip(pets,numbers):
pet_number_dict[animal]= num
print(pet_number_dict)
{'dog': 2, 'cat': 4, 'guinea pig': 10, 'parrot': 2}
Example-3: Using List Comprehension
pets= ['dog','cat','guinea pig', 'parrot']
numbers = [2,4,10,2]
pet_number_dict = {animal:num for animal,num in zip(pets,numbers)}
print(pet_number_dict)
{'dog': 2, 'cat': 4, 'guinea pig': 10, 'parrot': 2}
(12) How To Update A Dictionary
- The “update( )” Method Is Used To Update The Dictionary Values.
Example-1:
student = {'Name':'Subrat',
'Subject':'Math',
'Mark':88,
'Nationality':'Indian',
'Gender':'Male'
}
student.update({'Mark':99})
student
{'Name': 'Subrat',
'Subject': 'Math',
'Mark': 99,
'Nationality': 'Indian',
'Gender': 'Male'}
(13) Create A List Of Tuples From The Dictionary.
Example-1:
dict1 = { 1: 'a', 2: 'b', 3: 'c' }
lst1 = list(dict1.items())
print(lst1)
[(1, 'a'), (2, 'b'), (3, 'c')]
(14) How Can You Delete key-value Pair From Dictionary?
- Key-Value pair can be deleted by using ‘del’ keyword as shown below:
Example-1:
student = {'Name':'Subrat',
'Subject':'Math',
'Mark':88,
'Nationality':'Indian',
'Gender':'Male'
}
del student['Gender']
print(student)
{'Name': 'Subrat', 'Subject': 'Math', 'Mark': 88, 'Nationality': 'Indian'}