Python Dictionary

Dictionary is a method in which data is stored in pairs of keys and values. These are also called Associative Arrays in other programming languages.

 

What is key-value pair?

key is a unique identifier for a given record. Values are data stored in that identifier. For example, Let us say that Muneer is a student, and we want to create a dictionary containing his details. The first key in his record is name and the value for this key is ‘Muneer’. He has a weight of 75 Kg, therefore, the second key in this record is weight, and the value of this key is 75. His height is 6ft, and has age of 35 years. In this record, following are the key value pairs

  +-----------------+
  |   keys   values |
  |-----------------|
  |   name   Muneer |
  | weight       75 |
  | height        6 |
  |    age       35 |
  +-----------------+

 

How to create a dictionary

A dictionary is created using curly brackets. The first item is always the key followed by a full colon, the second item is the value. Next key-value pair is created using a comma.

In [2]:
student = {'name': 'Muneer', 'weight': 75, 'height': 6, 'age': 35}
In [3]:
student
Out[3]:
{'name': 'Muneer', 'weight': 75, 'height': 6, 'age': 35}
In [13]:
student.get('name')
Out[13]:
'Muneer'
In [14]:
student.get('age')
Out[14]:
35
In [ ]: