Dictionary concept is used for association purpose.
We use dictionary data structure when there is an association required between two objects.
Values are stored pairwise in dictionary in the form of keys and values.
Key act as primary key (keys cannot be repeated).
Value repetition can be possible in dictionary data structure.
The nature of key and values can be heterogeneous.
Indexing and slicing cannot be used in dictionary.
There is no specific order for storing elements in the dictionary.
Dictionary is mutable data structure.
We can use add, delete and update methods in dictionary data structure.
Dictionary is denoted using {}.
How to create an empty dictionary??
d={}
print(type(d)) #<class 'dict'>
Empty dictionary can also be created using dict() method as shown below.
d=dict()
Storing values in dictionary:
d={1:"Mayank",2:"Aniket",3:"Prajapati"}
print(d)
Accessing elements of dictionary:
We can access the element of dictionary using for loop as shown below.
d={1:"mayank",2:"aniket",3:"prajapati"}
for x in d:
print(d[x],end=" ")
Output: mayank aniket prajapati
Accessing specific element using key in dictionary:
d={1:"mayank",2:"aniket",3:"prajapati"}
print(d[2]) # aniket
print(d[4]) # KeyError
We use dictionary data structure when there is an association required between two objects.
Values are stored pairwise in dictionary in the form of keys and values.
Key act as primary key (keys cannot be repeated).
Value repetition can be possible in dictionary data structure.
The nature of key and values can be heterogeneous.
Indexing and slicing cannot be used in dictionary.
There is no specific order for storing elements in the dictionary.
Dictionary is mutable data structure.
We can use add, delete and update methods in dictionary data structure.
Dictionary is denoted using {}.
How to create an empty dictionary??
d={}
print(type(d)) #<class 'dict'>
Empty dictionary can also be created using dict() method as shown below.
d=dict()
Storing values in dictionary:
d={1:"Mayank",2:"Aniket",3:"Prajapati"}
print(d)
Accessing elements of dictionary:
We can access the element of dictionary using for loop as shown below.
d={1:"mayank",2:"aniket",3:"prajapati"}
for x in d:
print(d[x],end=" ")
Output: mayank aniket prajapati
Accessing specific element using key in dictionary:
d={1:"mayank",2:"aniket",3:"prajapati"}
print(d[2]) # aniket
print(d[4]) # KeyError
Be First to Post Comment !
Post a Comment