Python Dictionary
A dictionary in python is a data structure which consists of key-value pairs. Each key is associated with a corresponding value.
Keys in a dictionary are unique but values may be duplicate.
A dictionary is unordered as opposite to lists and tuples meaning its items cannot be accessed using indexes but only through keys.
A python dictionary can be visualized as

Python dictionary keys and values
Dictionary Syntax
A dictionary is created by using curly braces({ and }) and enclosing key-value pairs between them.
A single key-value pair is separated by colon(:) and different set of key-value pairs are separated by a comma(,).

Examples of dictionary are

laptops = { “brand” : “Lenovo”, “disk” : “320GB”, “ram” : 8 }
phones = { “type” : “smartphone”, “company” : “Samsung”, “screensize” : 5.7}

Above example contains two different dictionaries.
It should be noted that keys and values in a dictionary need not be of same type. They can be strings, numbers, floats etc.

Order of items in a dictionary is not maintained.
Sometimes, a key-value pair may appear at first position and sometimes the same pair may appear last. That is why it is called unordered and do not provide index based access to its items.
Create empty dictionary
It is also possible to create or make an empty dictionary using curly braces only. An empty dictionary does not contain any items or key-value pairs.

Below is an example of empty dictionary.

emp_dict = {}

Another method of creating an empty dictionary is by using dict() method as shown below.

emp_dict = dict()

Access dictionary items
As mentioned earlier, values of a dictionary can be accessed by using their key names. Syntax to access a value is by using the name of dictionary followed by its key enclosed in square brackets as shown below.

# create dictionary
laptops = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 } 
print(laptop)             # print dictionary 
print(laptop["brand"])    # access value with key "brand"
print(laptop["ram"])      # access value with key "ram"
print(laptop["disk"])     # access value with key "disk"

Above code will output

{ “brand” : “Lenovo”, “disk” : “320GB”, “ram” : 8 }

Dictionary also contains a method get() which can be used to get value of a key. This method takes a string which is the key as an argument and returns the value associated with that key.
If there is no value for the given key, or  the key-value pair does not exist it returns None.

# create dictionary
laptops = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 }
val = laptop.get("brand")  # get the value for key "brand"
print(val)                 # prints "Leneovo"
val = laptop.get("screen") # get value for non-existent key
print(val)                 # prints "None"

Remember that trying to access an item with a non-existing key using get() method will return None and will not be an error.
But when accessing a non-existing key using square bracket notation will result in an error as

# create dictionary
laptops = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 }
print(laptop["screen"]) # get value for non-existent key

Above code when executed will result in an error, KeyError: ‘screen’

Modifying dictionary values
It is possible to change the value of a key after the dictionary is created. This is done by assigning updated value to the corresponding key as shown below

# create dictionary
laptop = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 }
print(laptop["brand"])      # prints "Lenovo"
laptop["brand"] = "Apple"   # modify value of key "brand"
print(laptop["brand"])      # prints "Apple"

It is not possible to change a key of dictionary, that is, you cannot change the key “brand” to “model”. Only its value can be modified.

Add new items to dictionary
For adding a new key-value pair or element to a dictionary, write the name of the key in square brackets after the dictionary variable.

# create dictionary
laptop = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 }
print(laptop)   # print dictionary
laptop["size"] = "32 inches" # create a new key-value pair
print(laptop)   # print updated dictionary

This is the same syntax as updating a dictionary value. Only difference is that the key does not already exist. In this case, python adds an entry with this key to the dictionary.

Above code will produce following output

{ “brand” : “Lenovo”, “disk” : “320GB”, “ram” : 8}
{ “brand” : “Lenovo”, “disk” : “320GB”, “ram” : 8, “size” : “32 inches” }

Notice, a new key-value pair is added to the dictionary.

Removing items from dictionary
Sometimes it is required to remove a particular key-value pair from the dictionary. There are three ways of doing that.

1. Using del command
Write the dictionary name followed by the name of key enclosed in square brackets after del command. This will remove this key-value pair from dictionary.

Always remember to provide key name after dictionary when using del.
Using just the dictionary name with del will delete the entire dictionary and you will not be able to access it after that.
If you want to remove all key-value pairs from a dictionary and make it empty, then call clear method in the dictionary object.

# create dictionary
laptops = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 }
print(laptop)      # print dictionary
del laptop["ram"]  # remove item with key "ram"
print(laptop)      # print again
laptop.clear()     # remove all items
print(laptop)      # print empty dictionary
del laptop         # remove entire dictionary
print(laptop)      # print dictionary again   

Above program will give the following output.

{‘brand’: ‘Lenovo’, ‘disk’: ‘320GB’, ‘ram’: 8}
{‘brand’: ‘Lenovo’, ‘disk’: ‘320GB’}

NameError: name ‘laptop’ is not defined

Notice the error message at the last line. This is because we are accessing the dictionary after deleting it.
Also, a blank line in between indicates an empty dictionary since clear method was called before that.

2. Using pop() method
pop() method takes a string as argument which represents the key of item to be removed. Example,

# create dictionary
laptops = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 }
print(laptop)      # print dictionary
laptop.pop("disk")  # remove item with key "disk"
print(laptop)      # print again

Output will be

{ “brand” : “Lenovo”, “disk” : “320GB”, “ram” : 8 }
{ “brand” : “Lenovo”, “ram” : 8}

Notice the item with key “disk” is removed.

3. Using popitem() method
popitem() method removes the last inserted key-value pair from the dictionary. It also returns the item removed. Example,

# create dictionary
laptops = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 }
print(laptop)                 # print dictionary
laptop["screen"]= "32 inches" # add a new item with key "screen"
item = laptop.popitem()       # remove last inserted item
print(item)                   # prints "{ 'screen', '32 inches'}"

Iterate dictionary
There are different ways to iterate through a python dictionary using for loop as explained below.
1. Using for-in loop
Simply write a for-in loop over the dictionary as shown below.

# create dictionary
laptops = { "type" : "smartphone", "company" : "Samsung", "screensize" : 5.7}
for key in laptops:
    print('Key:', key,', Value:',laptops[key])

In every iteration, the variable placed before in will contain the current key out of a key-value pair. Above code outputs

Key: type , Value: smartphone
Key: company , Value: Samsung
Key: screensize , Value: 5.7

2. Using items() method
items() method returns a set of tuples where each tuple is a key-value pair of the dictionary. A for loop can be used to iterate over the set returned by the items() method. Example,

# create dictionary
laptops = { "type" : "smartphone", "company" : "Samsung", "screensize" : 5.7}
for key, value in laptops.items():
    print('Key:', key, ', Value:', value)

Variables key and value placed after for loop contain the key and value in every iteration. Behind the scenes, it is unpacking the tuple.
Output is

Key: type , Value: smartphone
Key: company , Value: Samsung
Key: screensize , Value: 5.7

3. Using keys() method
keys() method returns a set view of all dictionary keys which can be iterated using a for loop as in the example program below.

# create dictionary
laptops = { "type" : "smartphone", "company" : "Samsung", "screensize" : 5.7}
for key in laptops.keys():
    print('Key:', key, ', Value:', laptops[key])

In every iteration, key variable contains the key for the current dictionary item. Output of this program is

Key: type , Value: smartphone
Key: company , Value: Samsung
Key: screensize , Value: 5.7

Dictionary comprehension
Dictionary comprehension is a short hand method of creating a dictionary dynamically.

Suppose we want to create a dictionary from a for loop where key is a number and value = key + 2. Simple code would be

# create an empty dictionary
nums = {}
# for loop
for num in range(5):
    # add key-value pairs
    nums[num] = num + 2

Same dictionary can be created using dictionary comprehension as below.

nums = { num: num + 2 for num in range(5) }

which prints

{0: 2, 1: 3, 2: 4, 3: 5, 4: 6}

You can see that dictionary comprehension is much shorter and cleaner.

Its syntax is

dict_name = { key_expr : value_expr for key in range(5) }

key_expr and value_expr represent key and value of dictionary. These are expressions that resolve to some value.
These expressions are followed by a for loop. Number of items in a dictionary is equal to the number of times for loop executes.
Expressions and for loop are enclosed between curly braces and key and value expressions are separated by a colon(:). This is the basic syntax of a dictionary.
Dictionary methods
Below is a list of methods or functions in a python dictionary.

S. No.MethodDescription
1.dict()Creates an empty dictionary.
2.clear()Removes all items from dictionary.
3.copy()Creates a copy of dictionary. Copy is a shallow copy which means that if there are nested objects, then they are not copied.
4.get(key)Returns a value for the given key. If there is no item with the given key, then None is returned.
Provide a default value separated by a comma after the key if you do not want to return None as get(key, default).
5.fromkeys(iterable, value)Returns a dictionary with keys from an iterable.
Iterable may be a string in which case, the keys will be the characters of string or a list in which case, the keys will be the elements of the list.
All the keys will have the same values provided as second argument. If no value is provided, then value will be None.
Example, dict.fromkeys('codippa') will create a dictionary { 'c': None, 'o': None, 'd': None, 'i': None, 'p': None, 'p': None, 'a': None, }.
6.items()Returns a set view of key-value pairs of the dictionary.
If you check the type of value returned by items() using type function, then it is of type dict_items.
7.keys()Returns a set view of keys of the dictionary.
If you check the type of value returned by keys() using type function, then it is of type dict_keys.
8.pop(key)Removes the item with the supplied key as argument and returns the value associated with that key.
If the key is not found, then it will raise a KeyError.
To avoid KeyError, provide a default value to be returned as second argument, if the key is not found.
9.popitem()Removes and returns a random key-value pair from the dictionary.
Raises a KeyError if the dictionary is empty.
10.update(d)Updates the dictionary with the key-value pairs from the dictionary supplied as argument.
If the argument dictionary has some extra key-value pairs, then those are added to the current dictionary.
If the argument dictionary and current dictionary have common keys, then their values from argument dictionary are updated in  the current dictionary.
11.values()Returns a set view of values of the dictionary.
If you check the type of value returned by values() using type function, then it is of type dict_values.
Check if key exists
In order to check if a key exists in a dictionary or not, use the in operator. It will return True if the key exists and False if it does not. Example,

laptops = { "type" : "smartphone", "company" : "Samsung", "screensize" : 5.7}
print("type" in laptops)
print("price" in laptops)

if "screensize" in laptops:

Above example will print


Length of dictionary
Length of dictionary is the number of items or key-value pairs in it. Dictionary length can be determined using len() function as shown below.

laptops = { "type" : "smartphone", "company" : "Samsung", "screensize" : 5.7}

which prints


Hope this tutorial on python dictionary was useful.

Liked the article ? Spread the word...

Leave a Reply