Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered, changeable and do not allow duplicates.
Note: In Python 3.6 and earlier, dictionaries are unordered. As of version 3.7 these are ordered.
Dictionaries are written with curly brackets and have keys and values.
- Keys must only have one component.
- Values can be of any type, including integer, list and tuple.
Creating the Dictionary:
Although there are other methods to create a dictionary, curly brackets are mostly used to create a dictionary in Python. There are many key value pairs surrounded in curly brackets and a colon(:) separates each key from its value and each key value pair separated from each other by comma(,).
In this way a dictionary is formed.
Syntax of a dictionary is:
Dictionary={"Name":"Rishikesh", "Country":"Singapore"}
In above example, Name and Country are keys and Rishikesh and Singapore are their values respectively.
Let's see an example:
Example1
Emp_detail={"Name":"Surya", "EmpId":101, "Dept":"Sales", "City":"Lucknow"} print(type(Emp_detail))
|
---|
Output:
<class 'dict'> Printing the employee detail... {'Name':'Surya', 'EmpId':101, 'Dept':'Sales', 'City':'Lucknow'} |
---|
Example2
Dict={ "Brand":"Ford", "Year":1964, "Model":"Mustang" } print(type(Dict))
|
---|
Output
<class 'dict'> Printing the vehicle detail... {'Brand':'Ford', 'Year':1964, 'Model':'Mustang'} |
---|
Python provides the built-in function dict() method which is also used to make a dictionary.
The empty curly bracklets{} is used to create empty dictionary.
Code:
#Creating an empty dictionary Dict={} print("Empty Dictionary") print(Dict) #Creating a dictionary with dict() method Dict=dict({101:'Johnson', 102:'Sriniwasan', 103:'Peterson'}) print("Dictionary is created by dict() method") print(Dict)
|
---|
Output
Empty Dictionary {} Dictionary is created by dict() method {101:'Johnson', 102:'Sriniwasan', 103:'Peterson'}) Dictionary is created by each item as a pair method {104: 'Sudarshan', 105: 'Abraham'} |
---|
Accessing the dictionary values:
Data contained in list or tuple can be accessed by indexing. In the same manner keys of the dictionary are used to access the values because they are unique from one another.
Let's see an example to obtained the values from keys of a dictionary:
Code:
#Creating a dictionary Dict={"Name":"Shruti", "Age":22, "Salary":49000, "Company":"Wipro"} print(type(Dict)) print("Printing Employee data...") print("Name:%s"%Dict["Name"]) print("Age:%d" %Dict["Age"]) print("Salary:%d"%Dict["Salary"])
|
---|
Output
<class' dict'> Printing Employee data... Name:Shruti Age:22 Salary:49000 Company:Wipro |
---|
Python provides us with an alternative to use the get() method to access a dictionary value. It would give the same result as given by the indexing.
Adding Dictionary Values:
Python dictionary is a mutable data type and by using its syntax we can change or modify the values. An existing value can also be updated by update() method
Example1:
#Creating an empty dictionary Dict={} print("Empty Dictionary") print(Dict) #Adding elements to dictionary Dict["Name"]='Peter' Dict["Country"]='Netherland' Dict["Deptt"]='Sales' print("\nDictionary after adding three elements") print(Dict) #Adding set of value Dict["Emp_age"]=24 print("\nDictionary after adding one element") print(Dict) #Updating existing key's value Dict["Country"]='Bharat' print("\nDictionary with updated key value") print(Dict) |
---|
Output
Empty Dictionary {} Dictionary after adding three elements {'Name':'Peter', 'Country': 'Netherland', 'Deptt': 'Sales'} Dictionary after adding one element {'Name':'Peter', 'Country': 'Netherland', 'Deptt': 'Sales', 'Emp_age':24} Dictionary with updated key value {'Name':'Peter', 'Country': 'Bharat', 'Deptt': 'Sales', 'Emp_age':24} |
---|
Example2:
Employee={"Name":"Dev", "Age":20, "Salary":45000, "Company":"Wipro"} print(type(Employee)) print("Printing employee data...") print(Employee) print("Enter the details of the new employee...") Employee["Name"]=input("Name:"); Employee["Age"]=int(input("Age:")); Employee["Salary"]=int(input("Salary:")); Employee["Company"]=input("Company:"); print("printing the new data..."); print(Employee) |
---|
Output
<class 'dict'> Printing employee data... Employee={"Name": "Dev", "Age": 20, "Salary": 45000, "Company": "Wipro"} Enter the details of the new employee... Name:Peter Age:35 Salary:39000 Company:Excel printing the new data... Employee={'Name': 'Peter', 'Age': 20, 'Salary': 39000, 'Company': 'Excel'} |
---|
Deleting Elements using del keyword:
The items of the dictionary can be deleteed by using the Del keyword as given below.
Employee={"Name":"Dev", "Age":20, "Salary":45000, "Company":"Wipro"} print(type(Employee)) print("Printing employee data...") print(Employee) print("Deleting some of the employee data...") del Employee["Name"] del Employee["Company"] print("printing the modified data...") print(Employee) print("Deleting the dictionary Employee..."); del Employee print("Let's try to print it again"); print(Employee) |
---|
Output
<class 'dict'> Printing employee data... Employee={"Name": "Dev", "Age": 20, "Salary": 45000, "Company": "Wipro"} Deleting some of the employee data... printing the modified data... {'Age': 20, 'Salary': 45000} Deleting the dictionary Employee... Let's try to print it again NameError: name 'Employee' is not defined. |
---|
The last print statement in above code shows an error message because we tried to print the Employee dictionary that already deleted.
Deleting Elements using pop() method:
The pop() method in Python dictionary is one of the way by which we can retrieve, insert or remove items using their keys. Here we will discuss how to remove items from a Python dictionary using pop() method.
Code:
#Creating a dictionary Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"} print(Dict) #Deleting a key using pop() method pop_key=Dict.pop(2) print("printing modified data")
|
---|
Output
{1:'Shruti', 2:'Hasan', 3:'Jaspreet', 4:'Yasmin'} Printing modified data {1:'Shruti', 3:'Jaspreet', 4:'Yasmin'} |
---|
Python offers two built-in functions popitem() and clear() for removing dictionary items. But clear() function removes all the items from a dictionary whereas popitem() removes any element from a dictionary.
Iterating a Dictionary
A dictionary can be iterated using for loop. Let's understand by an example:
Example1
Code:
#for loop to print all the keys of a dictionary Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"} for i in Dict:
|
---|
Output
1 2 3 4 |
---|
Example2
Code:
#for loop to print all the values of a dictionary Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"} for i in Dict:
|
---|
Output
Shruti Hasan Jaspreet Yasmin |
---|
Example3
Code:
#for loop to print all the values of a dictionary using values() method Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"} for i in Dict.values():
|
---|
Output
Shruti Hasan Jaspreet Yasmin |
---|
Example4
Code:
#for loop to print all the items of a dictionary using items() method Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"} for i in Dict.items():
|
---|
Output
(1, 'Shruti') (2, 'Hasan') (3, 'Jaspreet') (4, 'Yasmin') |
---|
Properties of Dictionary Keys:
1. In the dictionary, we cannot store multiple values for the same keys. If we pass more than one value for a single key, then the value which is last assigned is considered as the value of the key.
Consider the following example:
Code:
Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin", 1:"Karanpreet"} for x,y in Dict.items():
|
---|
Output
1 Karanpreet 2 Hasan 3 Jaspreet 4 Yasmin |
---|
2. The key cannot belong to any mutable object in Python, Numbers, Strings, or Tuples can be used as the key, however mutable objects like lists cannot be used as the key in a dictionary.
Consider the following example:
Code:
Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin", 1:"Karanpreet", [101,102]:"Department ID"} for x,y in Dict.items():
|
---|
Output
1 Karanpreet 2 Hasan 3 Jaspreet 4 Yasmin |
---|
Built-in Dictionary Functions:
A function is a method that can be used on a construct to yield a value. Additionally, the construct is unultered. A few of the Python methods can be combined with a Python dictionary.
The built-in Python dictoinary methods are listed below, along with a brief description.
- len()
The dictionary's length is returned via the len() function in Python. The string is lengthened by one for each key-value pair.
Code:
Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"} len(Dict) |
---|
Output
4 |
---|
- any()
LIke how it does with lists and tuples, the any() method returns True indeed if one dictionary key does have a Boolean expression that evaluates to True.
Code:
Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"} any({".", ".", "3", "."}) |
---|
Output
True |
---|
- all()
Unlike in any() method, all() only returns True if each of the dictionary's keys contain a True Boolean value.
Code:
Dict={1:"Shruti", 2:"Hasan", 3:"Jaspreet", 4:"Yasmin"} all({1:' ',2:' ',' ':''}) |
---|
Output
True |
---|
- sorted()
The sorted method returns an ordered series of the dictionary's keys. The ascending sorting has no effect on the original Python dictionary.
Code:
Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"} sorted(Dict) |
---|
Output
[1, 3, 5, 7] |
---|
Built-in Dictionary methods
The built-in Python dictionary methods along with the description and Code are given below:
- clear()
It is used to delete all the items of the dictionary.
Code:
#Dictionary methods Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"} #clear() method Dict.clear() print(Dict) |
---|
Output
{} |
---|
- copy()
It returns a copy of the dictionary.
Code:
#Dictionary methods Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"} #copy() method Dict_demo=Dict.copy() print(Dict_demo) print(Dict) |
---|
Output
{5: 'Shruti', 7: 'Hasan', 3: 'Jaspreet', 1: 'Yasmin'} {5: 'Shruti', 7: 'Hasan', 3: 'Jaspreet', 1: 'Yasmin'} |
---|
- pop()
It mainly eliminates the element except one using the defined key.
Code:
#Dictionary methods Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"} #pop() method Dict_demo=Dict.copy() x=Dict_demo.pop(1) print(x)
|
---|
Output
Yasmin Shruti |
---|
- popitem()
It prints the most recent key-value pair entered
Code:
#Dictionary methods Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"} #popitem() method Dict_demo=Dict.popitem() print(Dict_demo) |
---|
Output
(1, 'Yasmin') |
---|
- keys()
It returns all the keys of the dictionary
Code:
#Dictionary methods Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"} #keys() method print(Dict_demo.keys()) |
---|
Output
Dict_keys([5, 7, 3, 1]) |
---|
- items()
It returns all the key-value pair as a tuple.
Code:
#Dictionary methods Dict={5:"Shruti", 7:"Hasan", 3:"Jaspreet", 1:"Yasmin"} #item() method print(Dict_demo.item()) |
---|
Output
Dict_items([(5, 'Shruti'), (7, 'Hasan'), (3, 'Jaspreet'), (1, 'Yasmin')]) |
---|