Dictionary in Python

Dictionary provides a very convenient way to store data in an order like a List but it allow you stores data in key value pair.

# Declare a dictionary 
name_of_dictionary{key:value}

name of the dictionary, curly braces “{ }”, key and value in it. Let’s have a look at real example:

# Declare the dictionary
mydictionary = {'name' : "Khan"}

# print the value by using key
print(mydictionary['name'])

You have a dictionary called mydictionary, mydictionary contains a key which is name and this key has an associated value Khan with it. To access the value ‘Khan’, call mydictionary[‘name’] as mentioned in this example. 

mydictionary = {"name" : "Khan" , "address" : "Stockholm" , "job" : "Software Engineering"}

print("My name is " + mydictionary["name"] + 
" i live in " + mydictionary["address"] + 
" and i am " + mydictionary["job"])

You can add as many key value pairs as you want.

Add / Update dictionary

More values can be added to the dictionary as well as existing values can be updated. 

## Add more key value pair
mydictionary["country"] = "Sweden"
print(mydictionary["country"])

## update the existing value
mydictionary["name"] = "Abid Khan"

Notice that syntax to adding new value or updating the existing one is the same. If a key in dictionary already exists then the value will be replaced with new one otherwise new key value pair will be inserted.

Remove / Clear dictionary

Any key:value pair can be removed from the dictionary by using del command, pass the dictionary with key and it will be removed from list. 

del mydictionary["address"]

## following line will throw error
print(mydictionary["address"])

All values from dictionary can be removed by using clear function. Remember that clear function removes only contents of the dictionary not dictionary itself.

# get dictionary length
print("Dictionary length is " + str(len(mydictionary)) )

# clear all dictionary
mydictionary.clear()

print("Dictionary length is " + str(len(mydictionary)) )

Array of Values 

Python is a flexible language, it allows you to add array of values against one key.

# Declare the 
name_of_dictionary{key:[array of values]}

Add a key value pair and add a simple array as a value. Create a new dictionary called mydict and add a key with array as a value in it.

# create dictionary with array

mydict = {'info':['Khan', 35, "Stockholm"]}

Added array as a value is a normal array which can accessed by zero based index, following example shows how to access array values.

# print dictionary

print("My name is " + mydict["info"][0] + " i am " + str(mydict["info"][1]) + " years old, i live in " + mydict["info"][2])

You can add normal key value pair in this dictionary as well.

mydict = {'info':['Khan', 35, "Stockholm"], 'country': 'Sweden'}

print("My name is " + mydict["info"][0] + " i am " + str(mydict["info"][1]) +
      " years old, i live in " + mydict["info"][2] + 
      " and i love " + mydict['country'])


Some important functions 

Dictionary always contains key value pair and these values can be fetched by using keys. But if key does not exist, program will throw key error. For example mydictionary contains a key called language and value related to this key is Python. 

# Add new key value pair

mydictionary["language"] = "Python"
print(mydictionary["language"])

Print statement will display Python as output. What if you type Language instead of language in print statement. Program will crash and you will get key error message.

get method
Python provides a get method to avoid program crash. get method takes two parameters, first parameter is the key and second is default value. If key does exist in dictionary, default value will be returned. 

# get method with existing key
print(mydictionary.get("language", "Record not found"))
# get method with non-existing key
print(mydictionary.get("Language", "Record not found"))

keys, values and items methods
keys method return complete list of keys in a dictionary, values method return all values and items method returns key and value both.

# get keys
print(mydictionary.keys())

# get values
print(mydictionary.values())

# get pairs
print(mydictionary.items())

update methods
update method helps to combine two dictionaries. See this simple example.

dict1 = {'name' : "Khan"}
dict2 = {'address' : "Stockholm"}

print(dict1.items())

dict1.update(dict2)

print(dict1.items())