python

Python collection - Dictionaries in python

The Python dictionary is used to store data in a key: value pair form. The dictionary is created using the curly brackets in python.

my_dict = {
    "first_name": "John",
    "last_name": "Deo",
    "occupation": "programmer"
}

print(my_dict["first_name"]) #print first_name value of dictionary

print(my_dict.get("first_name")) #same as above

my_dict["first_name"] = "Josef" #To change first_name value

my_dict.values() #return values of dictionary

my_dict["nick_name"] = "JDo" #To add key value to dictionary

my_dict.pop("last_name") #To remove a key value pair from dictionary based on key

del my_dict["last_name"] #Same as above

my_dict.clear() #empty a dictionary

my_dict.copy() #To copy a dictionary

Dictionaries in python represent a key-value pair datastore in a variable. You can access the value of the dictionary item by its key name. You can also change and remove items from a dictionary using a key name. 

If you are using Python version 3.7 and higher, the dictionary will be ordered, and for version 3.6 and lower the dictionary will be unordered.

A dictionary can not contain duplicate items.

subject = {
  'name': 'Math',
  'score': 100,
  'code': 'Math001',
  'lessons': 20
}

for key in subject:
    print(key, 'is ', subject[key])

# -> name is  Math
# -> score is  100
# -> code is  Math001
# -> lessons is  20
We can loop through a dictionary as the above code snippet.
Was this helpful?