How Can We Help?
A dictionary(dict) is a data type that can hold an unordered set of key-value pairs. For example, Age-15, Animal-Lion, Car-Honda, etc. It is enclosed in pair of curly braces({}).
The dictionary key works as an index, and the user decides it. The value of the dictionary is decided against the respective key index, like Animal is a key and Lion is a value of it. The key and value are separated from each other by a colon (:), and multiple (key-value) pairs are separated from each other by a comma(,).
Dictionary Syntax:
<dictionary_variable_name> = {key1:value1, key2:value2, .......}
Example (1)
>>> dict={'Country':'India','State':'Gujarat','City':'Vadodara'}
>>> print(dict)
Output:
{‘Country’: ‘India’, ‘City’: ‘Vadodara’, ‘State’: ‘Gujarat’}
In the above example, “dict” is the dictionary variable, “Country, State, and City” are keys, and “India, Gujarat, and Vadodara’ are values of the dictionary variable “dict“.
Is Python Dictionary Ordered or Unordered?
Starting from Python version 3.7, the dictionary is ordered; however, in Python 3.6 and earlier, dictionaries are unordered.
Unordered Dictionary
In python, the dictionary has no concept of order among elements; it is simply unordered. The order of elements in the output may be different from the input. In the above example, as an input , {‘Country’:’India’,’State’:’Gujarat’,’City’:’Vadodara’} but in output, {‘Country’: ‘India’, ‘City’: ‘Vadodara’, ‘State’: ‘Gujarat’}.The order of the key-value pair is changed.
Note: The keys must be unique in the dictionary, and two keys are not the same for a single dictionary. See the below example.
Example (2)
>>> places={'Country':'Europe','Country':'UK','City':'London'}
>>> print(places)
Output:
{‘Country’: ‘UK’, ‘City’: ‘London’}
In the above example, for the dictionary variable ‘places’, the key index Country=UK overrode with another key index Country=Europe, resulting in output with only one key index as Country=UK. So we can say that the key index should be unique and different from other key indexes or when duplicate keys are used during the assignment, the last assignment is as output.
Note: Keys must be immutable means we can use strings, numbers, or tuples as dictionary keys, but something like a list, i.e. [‘key’], is not allowed. See below for examples of the List and tuple keys.
Example (3)
>>> places={['Country']:'UK','City':'London'}
Output:
Traceback (most recent call last):
File “”, line 1, in
places={[‘Country’]:’UK’,’City’:’London’}
TypeError: unhashable type: ‘list’
In the above example, we are using the list key index as [‘Country’] for the dictionary variable ‘places’, so we got a type error in the output.
Example (4)
>>> places={('Country'):'UK','City':'London'}
>>> print(places)
Output:
{‘Country’: ‘UK’, ‘City’: ‘London’}
In above Example, we are using tuple key index as (‘Country’) for dictionary variable ‘places’ so output is dictionary value as places={‘Country’: ‘UK’, ‘City’: ‘London’}.
Define Python Dictionary Key Index
To define the key index, create an empty dictionary and then add key-value pair to the empty dictionary.
Example (5)
StudentData={}
StudentData ['Year']= 'FY'
StudentData ['TotalStudent']=60
print('First Year detail: ', StudentData)
Output:
First Year detail: {‘TotalStudent’: 60, ‘Year’: ‘FY’}
In the above example, the resulted output shows the added key-value pair in dictionary as StudentData= {‘TotalStudent’: 60, ‘Year’: ‘FY’}.
How to use List and Tuples with Python Dictionary
We can assign lists and tuples as values against the key index in the dictionary in two ways.
- Single Assignment
- Multiple Assignments
Single Assignment
Example (6)
CollegeData={}
CollegeData['Stream']= 'BE'
CollegeData['TotalStudent']=300
CollegeData['DeptName']=['IT','CSE','EC']
print('CollegeStreamData: ',ColledgeData)
Output:
CollegeStreamData: {‘DeptName’: [‘IT’, ‘CSE’, ‘EC’], ‘Stream’: ‘BE’, ‘TotalStudent’: 300}
In the above Example , for dictionary variable ‘CollegeData’, list values is [‘IT’,’CSE’,’EC’] assigned against key index ‘DeptName’ by CollegeData[‘DeptName’]=[‘IT’,’CSE’,’EC’].
Example (7)
CollegeData={}
CollegeData['Stream']= 'BCom'
CollegeData['Section']=('A','B','C','D')
CollegeData['TotalStudent']=400
print('CollegeStreamData: ',CollegeData)
Output:
CollegeStreamData: {‘Stream’: ‘BCom’, ‘Section’: (‘A’, ‘B’,’C’,’D’), ‘TotalStudent’: 400}
In the above Example, for dictionary variable ‘CollegeData’ , tuple values as (‘A’,’B’,’C’,’D’) assigned against key index ‘Section’ by CollegeData[‘Section’]=(‘A’,’B’,’C’,’D’).
Multiple Assignment
Example (8)
Students={}
Students['Arts','Commerce','Science']=[50,100,200]
Students['IT','CSE','EC']=(30,50,60)
print('Student count in respective department: ', Students)
Output:
Student count in respective department: {(‘Arts’, ‘Commerce’, ‘Science’): [50, 100, 200], (‘IT’, ‘CSE’, ‘EC’): (30, 50, 60)}
In the above Example , key-value pair of dictionary is Arts=50, Commerce=100, Science=200, IT=30,CSE=50 and EC=60.
Accessing Python Dictionary
We can access the dictionary value by its key index.
Example (9)
Data={'Standard':'9th','Section':'A','StudentName':'Sam'}
print('Section of student:',Data['Section'])
Output:
Section of student: A
In the above example,’ Section’ is a key index of dictionary variable ‘Data’, and its access in a print statement by Data[‘Section’], so the output is ‘A’.
Built-In Python Dictionary Functions
Python has the following built-in dictionary functions.
- Length of Dictionary len(dict): It returns the total length of a dictionary, which is equal to the number of items in the dictionary.
- Comparing Dictionary dict1.keys() & dict2.keys(): It returns keys or items value according to the comparison of the key-value pair of a dictionary.
- Convert Dictionary into String str(dict): It returns a printable string representation of a dictionary.
- Type of Dictionary type(dict): It returns the type of dictionary if a passed variable is a dictionary.
How to Get Length of a Python Dictionary
We use the len() function to calculate the length of a dictionary. It returns a total length of a dictionary, which is equal to the number of items in the dictionary.
Example (10)
Data={'Totalmarks': 300, 'TotalSubject': 6}
print('length of dictionary:',len(Data))
Output:
length of dictionary: 2
In the above example, the dictionary variable ‘Data’ has two key-value pairs, i.e., its length is 2, which we got by len(Data), so the output is “2”.
Comparing Python Dictionary
We can compare two dictionaries using the intersection method of set theory, like finding common pairs/keys in both dictionaries or finding unique keys of one dictionary in another.
Example (11)
Data1={'India':'Mumbai','USA':'New York', 'UK':'London'}
Data2={'GJ':'Baroda','RJ':'Jaipur','AP':'Hyderabad','India':'Mumbai'}
print('Common keys: ', Data1.keys() & Data2.keys())
print('Common key-value pairs:', Data1.items() & Data2.items())
print('Keys are in Data1 but not in Data2:',Data1.keys() - Data2.keys())
print('Keys are in Data2 but not in Data1:',Data2.keys() - Data1.keys())
Output:
Common keys: {‘India’}
Common key-value pairs: {(‘India’, ‘Mumbai’)}
Keys are in Data1 but not in Data2: {‘USA’, ‘UK’}
Keys are in Data2 but not in Data1: {‘RJ’, ‘AP’, ‘GJ’}
In the above example, ‘Data1’ and ‘Data2’ are dictionary variables. “India” is common key for both dictionaries and “India : Mumbai” is common key-value pair for both dictionaries, so output shows these result after running command as “Data1.keys() & Data2.keys()” and “Data1.items() & Data2.items()”. {‘USA’, ‘UK’} uncommon keys are available in ‘Data1’ but not in ‘Data2’ , so output of difference between ‘Data1’ and ‘Data2’ shows {‘USA’, ‘UK’}.
Note: In python 2, cmp(dict1,dict2) is used to compare two dictionaries. If dict1 = = dict2, result is 0; if dict1> dict2, result is 1 and if dict1< dict2, result is -1.
Convert the Dictionary into a String
We can convert the dictionary into a string by the str() function. It returns a printable string representation of a dictionary.
Example (12)
data={'A':'apple','B':'bat'}
print(str(data))
Output:
“{‘B’: ‘bat’, ‘A’: ‘apple’}”
In the above example, ‘str(data)’ converts a dictionary ‘data’ into a string.
Get the Type of Dictionary
We can get the dictionary type by passing the dictionary variable in the type() function.
Example (13)
data={'A':'apple','B':'bat'}
print('Type of data:', type(data))
Output:
Type of data: <class ‘dict’>
In the above example, ‘type(data)’ is used to get the variable ‘data’ type.
Built-In Dictionary Methods
Python has the following built-in dictionary methods.
Function | Description |
---|---|
dict1.update(dict2) | It returns a merged dictionary which includes items of dictionary 1 and dictionary 2. |
del dict del dict[key] | It deletes all elements of the dictionary. |
dict.clear() | It removes all elements of the dictionary but does not delete them. |
dict.get(key, default=None) | It returns the value of the passed key of the dictionary. If the key does not exist in a dictionary, it returns None as default. |
dict.setdefault(key, default=None) | It is used to set the value against the not-present key of the dictionary. |
dict.copy() | It returns a shallow copy of the dictionary. |
dict.fromkeys(seq[, value]) | It returns a new dictionary with keys as a sequence and value as the given value. |
key in dict | It returns True if the given key is present in the dictionary; otherwise returns False. |
dict. keys() | It returns all keys to a dictionary. |
dict. values() | It returns all values of the dictionary. |
dict. items() | It returns all key-value pairs of a dictionary. |
Updating Python Dictionary
We can update a dictionary by modifying an existing entry of value or adding a new entry of a key-value pair, or merging two dictionaries.
Modify Python Dictionary
To modify the dictionary, change the value against a respective key index.
Example (14)
SchoolData={'Standard': '1st', 'Section': 'A', 'TotalStudent': 60}
SchoolData['Standard']= '3rd' # modify value
print('Updated School Data:',SchoolData)
Output
Updated School Data: {‘TotalStudent’: 60, ‘Section’: ‘A’, ‘Standard’: ‘3rd’}
In the above Example, we changed the value of key index ‘Standard’ from ‘1st’ to ‘3rd’ by SchoolData[‘Standard’]= ‘3rd’ in dictionary variable ‘SchoolData’ so output is modified dictionary as “Updated School Data: {‘TotalStudent’: 60, ‘Section’: ‘A’, ‘Standard’: ‘3rd’}”.
Add New Key-Value Pair
Add a key-value pair by assigning a new key index to add a new dictionary entry.
Example (15)
SchoolData={'Standard': '1st', 'Section': 'A', 'TotalStudent': 60}
SchoolData['StudentName']= 'Sam' #Add new key-value pair
print('Updated School Data:',SchoolData)
Output:
Updated School Data: {‘Standard’: ‘1st’, ‘TotalStudent’: 60, ‘Section’: ‘A’, ‘StudentName’: ‘Sam’}
In the above Example , we added ‘StudentName’ key index with its value as ‘Sam’ by SchoolData[‘StudentName’]= ‘Sam’ in dictionary variable ‘SchoolData’ so output has updated dictionary as “SchoolData={‘Standard’: ‘1st’, ‘TotalStudent’: 60, ‘Section’: ‘A’, ‘StudentName’: ‘Sam’}”.
Merge Python Dictionaries
We can merge two dictionaries by dict1.update(dict2) method and returns a new dictionary with all key values of both dictionaries.
Example (16)
SchoolData1={'Standard': '1st', 'Section': 'A', 'TotalStudent': 60}
SchoolData2={'Name': 'Bosch', 'Owner': 'Robert Bosch'}
SchoolData1.update(SchoolData2) #merge dictionaries
print('Updated School Data:',SchoolData1)
Output
Updated School Data: {‘Owner’: ‘Robert Bosch’, ‘Section’: ‘A’, ‘Standard’: ‘1st’, ‘TotalStudent’: 60, ‘Name’: ‘Bosch’}
In the above Example , we merged two dictionaries by ‘SchoolData1.update(SchoolData2)’ and got output as SchoolData1={‘Owner’: ‘Robert Bosch’, ‘Section’: ‘A’, ‘Standard’: ‘1st’, ‘TotalStudent’: 60, ‘Name’: ‘Bosch’}.
Deleting Dictionary
We use a del() function to perform a delete operation in the dictionary. We can either remove individual dictionary elements or delete the entire dictionary using it.
Delete Element of Dictionary
Example (17)
SchoolData={'Standard': '1st', 'Section': 'A', 'TotalStudent': 60, 'StudentName': 'Sam'}
del SchoolData['Standard'] # delete element of dictionary
print('Student data after deletion of standard:',SchoolData)
Output
Student data after deletion of standard: {‘StudentName’: ‘Sam’, ‘Section’: ‘A’, ‘TotalStudent’: 60}
In the above example, key index ‘Standard’ is deleted from dictionary variable ‘SchoolData’ by del SchoolData[‘Standard’] so output of the dictionary is “SchoolData= {‘StudentName’: ‘Sam’, ‘Section’: ‘A’, ‘TotalStudent’: 60}”.
We can’t delete multiple elements of the dictionary. See the below example.
Example (18)
SchoolData={'Standard': '1st', 'Section': 'A', 'TotalStudent': 60, 'StudentName': 'Sam'}
del SchoolData['Standard', 'Section'] # delete key
print('Student data after deletion of standard:',SchoolData)
Output:
Traceback (most recent call last):
File “C:\test.py”, line 2, in
del SchoolData[‘Standard’, ‘Section’] # delete key
KeyError: (‘Standard’, ‘Section’)
In the above example, if we are trying to delete multiple elements of the dictionary so, in the output, we get a KeyError.
Delete Whole Dictionary
Example (19)
SchoolData={'Standard': '1st', 'Section': 'A', 'TotalStudent': 60, 'StudentName': 'Sam'}
del SchoolData # delete the whole dictionary
print('Student data after deletion of standard',SchoolData)
Output:
Traceback (most recent call last):
File “”, line 1, in
print(‘Student data after deletion of standard’,SchoolData)
NameError: name ‘SchoolData’ is not defined
In the above example, we are deleting the dictionary variable ‘SchoolData’ by del SchoolData, so we received the output as an error, i.e. ‘SchoolData’ dictionary is not defined because the ‘SchoolData’ dictionary is deleted.
Clearing Dictionary
We use a clear() function to perform the clear operation in a dictionary. Using it, we can remove the entire contents of a dictionary but not delete it.
Example (20)
SchoolData={'Standard': '1st', 'Section': 'A', 'TotalStudent': 60, 'StudentName': 'Sam'}
SchoolData.clear()
print('Student data after clearing dictionary',SchoolData)
Output:
Student data after clearing dictionary {}
In the above Example, we clear dictionary variable ‘SchoolData’ by SchoolData.clear() and after performing the clear operation on dictionary variable ‘SchoolData’, we get empty “SchoolData={}” dictionary as output.
Get Dictionary Values
We use the get() method to get the values of a given key in a dictionary. If the key is unavailable, it returns the default value as ‘None’.
Example (22)
Data={'Name' : 'Sam', 'RollNumber':57}
print (" roll number value: %s" % Data.get('RollNumber'))
print ("name value: %s" % Data.get('Name'))
print (" Fail value: %s" % Data.get('Fail',"Never"))
Output:
roll number value: 57
name value: Sam
Fail value: Never
In the above example, ‘Data’ is a dictionary, and we get the value of the “Name” and
“RollNumber” key index in a print statement by the get() method, so the output shows the value of the respective key index as “roll number value: 57”, “name value: John” and “Fail value: Never”. Here, Fail=Never as key-value pair is added in the ‘Data‘ dictionary.
Copy Dictionary
We use the copy() method to create a shallow dictionary copy.
Example (23)
Data1={'Name' : 'Sam', 'RollNumber':57}
Data2=Data1.copy()
print ("New Dictionary : %s" % str(Data2))
Output:
New Dictionary : {‘RollNumber’: 57, ‘Name’: ‘Sam’}
In the above example, the Data2 dictionary is a shallow copy of the Data1 dictionary.
Get All Values in the Dictionary
We can use the values() function to get all values of the dictionary.
Example (24)
Login={'UN':'administrator','PW':'adminjlbets123'}
print('values:',Login.values())
Output:
values: dict_values([‘administrator’, ‘adminjlbets123’])
In the above example, “Login” is a dictionary variable, and Login.values() are used to get all values of dictionary Login.
Get All Items in the Dictionary
We can use the items() function to get all key-value pairs of a dictionary.
Example (25)
Login={'UN':'administrator','PW':'adminjlbets123'}
print('items:', Login.items())
Output:
items: dict_items([(‘UN’, ‘administrator’), (‘PW’, ‘adminjlbets123’)])
In the above example, “Login” is a dictionary variable, and Login.items() are used to get all items of dictionary Login.
In this tutorial, you have learned what is python dictionary and how to use it by giving 25+ Practical Examples to understand the concept very well.
If you have an inquiry or doubt don’t hesitate to leave them in the comment section. we are waiting for your feedback.But remember to understand the concept very well, you need to practice more.
Hopefully, it was clear and concise.