A Python dictionary is stored the data in the pair of key-value. It organizes the data in a unique manner where some specific value exists for some particular key. It is a mutable data-structure; its element can be modified after creation. Before creating a dictionary, we should remember the following points.
- Keys must be unique and must contain a single value.
- Values can be any type, such as integer, list, tuple, string, etc.
- Keys must be immutable.
Creating a Dictionary
The dictionary is created using the multiple key-value pair, which enclosed within the curly brackets {}, and each key is separated from its value by the colon (:). The syntax is given below.
Syntax:
dict1 = {“Name”: “James”, “Age”: 25, “Rollnu”: 0090001 }
In the above dictionary, the Name, Age, Rollnu are the keys which immutable object and James, 25, 0090001 are its values.
Let’s see the following example.
Example -
Student = {"Name": "John", "Age": 10, "Result":"Passed","Rollno":"009001"}
print(type(Student))
print("printing Employee data .... ")
print(Student)
Output:
<class 'dict'>
printing Employee data ....
{'Name': 'John', 'Age': 10, 'Result': 'Passed', 'Rollno': '009001'}
The empty curly bracket {} is used to create empty dictionary. We can also create dictionary using the built-in dict() function. Let’s understand the following example.
Example -
dict = {}
print("Empty Dictionary is: ")
print(dict)
# Creating a Dictionary
# using the dict() method
dict1 = dict({1: 'Hello', 2: 'Hi', 3: 'Hey'})
print("\nCreate Dictionary by using the dict() method : ")
print(dict1)
# Creating a Dictionary
# with each item as a Pair
dict2 = dict([('Devansh', 90014), ('Arun', 90015)])
print("\nDictionary with each item as a pair: ")
print(dict2)
Output:
Empty Dictionary is:
{}
Create Dictionary by using the dict() method :
{1: 'Hello', 2: 'Hi', 3: 'Hey'}
Dictionary with each item as a pair:
{'Devansh': 90014, 'Arun': 90015}
The dictionary is mostly used to store a large amount of data where we can access any value by its key.