Dictionary in Python

Last updated Aug 09, 2021

Dictionary

Dictionary is different from both list and tuple as it is an unordered collection of key-value pairs and is always written in key: value pair. It is also a built-in data type. These are used for retrieving data. A dictionary is always represented with curly brackets{ }. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

 

Let's take an example of Dictionary:-

a = {1:"Rohan", 2:"Sumit", 3:"Karan", 4:"Aman"}

print(a)

 

{1: 'Rohan', 2: 'Sumit', 3: 'Karan', 4: 'Aman'}

 

So you can see that we had obtained a dictionary.

Now let's take an other example of Dictionary:-


 

marks = {}.fromkeys(['Math', 'English', 'Science'], 0)

print(marks)

for item in marks.items():

     print(item)

print(list(sorted(marks.keys())))



 
{'Math': 0, 'English': 0, 'Science': 0}
('Math', 0)
('English', 0)
('Science', 0)
['English', 'Math', 'Science']

 

We hope that you got a better understanding of Dictionary in Python.

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

100 Views