Python Dictionary
Python Dictionary

Python Dictionary

A Python Dictionary is a Data Structure that stores value in form of key-value pair. It is a collection of python objects where each object comprises of a Key and its corresponding Value.

In other words, we can say that a Python dictionary is just like a real-life dictionary that stores all the words and their meanings as its data objects.

As we discussed Dictionary stores the data in key-value format. Here each key must be an immutable python object. It could be an object of integer, float, or string type but it must not be a mutable sequence. Whereas, a value could be anything including a list, tuple, or any other Python object.

How to create a Python dictionary?

In Python, we can create a dictionary using curly braces { }. We can create it by placing a sequence of items within the curly braces. Here, each dictionary item is a key-value pair. That means each item has a key and a value associated with that key.

Each item is written in the format – key: value. For example,

#creating dictionary
mydict = {'name':'Kush', 'age':24, 'profession':'chef'}
print(type(mydict))
print('Defined dictionary =', mydict)

Output:

<class 'dict'>
Defined dictionary = {'name': 'Kush', 'age': 24, 'profession': 'chef'}

In addition, Python provides a built-in method dict() which is used to create a dictionary. To use this method, we may first create an empty dictionary or else Python will automatically create one. After that, we simply need to pass the sequence of dictionary items to the dict() method. With the help of this method, we can even create a dictionary from a sequence of other collections. Here, each collection must have only two elements representing key and value. For example,

#creating dictionary by providing key-value pairs in curly braces
mydict = dict({'name':'Daksh', 'age':27, 'profession':'lawyer'})
print(type(mydict))
print('Dictionary from key-value pairs:', mydict)

#creating dictionary by providing a list of tuples
mydict2 = dict([('name', 'Rahul'), ('age', 35), ('profession', 'doctor')])
print(type(mydict2))
print('Dictionary from list of tuples:', mydict2)

#creating dictionary by providing a list of lists where each list has 2 elements
mydict3 = dict([['name', 'Kiran'], ['age', 24], ['profession', 'teacher']])
print(type(mydict3))
print('Dictionary from list of lists:', mydict3)

Output:

<class 'dict'>
Dictionary from key-value pairs: {'name': 'Daksh', 'age': 27, 'profession': 'lawyer'}
<class 'dict'>
Dictionary from list of tuples: {'name': 'Rahul', 'age': 35, 'profession': 'doctor'}
<class 'dict'>
Dictionary from list of lists: {'name': 'Kiran', 'age': 24, 'profession': 'teacher'}

How to access items of a Python dictionary?

We know that in the case of ordered sequences like Python List and Python Tuple, an item can be accessed using Indexing. But in the case of Python dictionary, we cannot use simple indexing. However, any item can be accessed by using its key. Since all keys are unique, we can access any value from its key.

We need to simply pass the key inside square brackets to get the dictionary item. In other words, we can say that here we use the key as an Index rather than a positional value.

In addition, there is also a built-in method get() used to retrieve dictionary value from its key.

Syntax – dictonary.get(key)

specs = {
    'Model': 'HP47077',
    'Processor': 'i5',
    'RAM': 8,
    'Touch display': False
}

#accessing value of 'Model' key from specs using key as index
print("Value of 'Model' key:", specs['Model'])

#accessing value of 'Processor' key from specs using get method
print("Value of 'Processor' key:", specs.get('Processor'))

Output:

Value of 'Model' key: HP47077
Value of 'Processor' key: i5

Apart from this, there are two built-in Python methods keys() and values(). keys() method will return a list of all keys in the dictionary and values() method will return a list of all values in the dictionary. For example,

fruits = {
    'apple': 'red',
    'banana': 'yellow',
    'guava': 'green',
    'cherry': 'red',
    'kiwi': 'brown'
}

#accessing keys of dictionary
keys_of_dictionary = fruits.keys()
print(keys_of_dictionary)

#accessing values of dictionary
values_of_dictionary = fruits.values()
print(values_of_dictionary)

Output:

dict_keys(['apple', 'banana', 'guava', 'cherry', 'kiwi'])
dict_values(['red', 'yellow', 'green', 'red', 'brown'])

How to add or modify items in a Python dictionary?

There are two ways we can add items in a Python dictionary. First, we can use a new key and assign it the value.

Syntax – dictionary[key] = value

This method is also used to update the value if the key is already present in the dictionary. For example,

mydict = {
    'name': 'George',
    'age': 47,
    'profession': 'actor'
}
print('Initial dictionary:', mydict)

#adding a new key value pair
mydict['place'] = 'Maryland'
print('Dictionary after adding new key-value pair:')
print(mydict)

#modifying existing value of key 'profession'
mydict['profession'] = 'producer'
print('Dictionary after modifying an item:')
print(mydict)

Output:

Initial dictionary: {'name': 'George', 'age': 47, 'profession': 'actor'}
Dictionary after adding new key-value pair:
{'name': 'George', 'age': 47, 'profession': 'actor', 'place': 'Maryland'}
Dictionary after modifying an item:
{'name': 'George', 'age': 47, 'profession': 'producer', 'place': 'Maryland'}

The second option we have is to use a built-in method update(). This method can both add a key-value pair as well as update the value in case the key is already present.

Syntaxdictionary.update({key: value})

For example,

mydict = {
    'name': 'Benedict',
    'age': 43,
    'profession': 'director'
}
print('Initial dictionary:', mydict)

#adding a new key value pair
mydict.update({'place': 'Texas'})
print('Dictionary after adding new key-value pair:')
print(mydict)

#modifying existing value of key 'profession'
mydict.update({'profession': 'actor'})
print('Dictionary after modifying an item:')
print(mydict)

Output:

Initial dictionary: {'name': 'Benedict', 'age': 43, 'profession': 'director'}
Dictionary after adding new key-value pair:
{'name': 'Benedict', 'age': 43, 'profession': 'director', 'place': 'Texas'}
Dictionary after modifying an item:
{'name': 'Benedict', 'age': 43, 'profession': 'actor', 'place': 'Texas'}

How to delete items of the Python dictionary?

We have three ways to delete items from the Python dictionary.

Using pop() and popitem() method

We can remove a specific key-value pair from the dictionary using pop() method. We simply need to provide the key to the method and it will remove the specified key and value.

Syntax – dictionary.pop(key)

In addition, Python also provides popitem() method. This method was originally used to remove an arbitrary item from the dictionary but after Python version 3.7 it is used to remove the last inserted element.

bikes = {
    'bullet': 'Royal Enfield',
    'apache': 'TVS',
    'pulsar': 'Bajaj',
    'hornet': 'Honda',
    'CBZ': 'Yamaha'
}
print("Original dictionary:")
print(bikes)

#removing item with key 'pulsar'
bikes.pop('pulsar')
print("Dictionary after removing 'pulsar':")
print(bikes)

#removing last item
bikes.popitem()
print("Dictionary after removing last item:")
print(bikes)

Output:

Original dictionary: 
{'bullet': 'Royal Enfield', 'apache': 'TVS', 'pulsar': 'Bajaj', 'hornet': 'Honda', 'CBZ': 'Yamaha'}
Dictionary after removing 'pulsar':
{'bullet': 'Royal Enfield', 'apache': 'TVS', 'hornet': 'Honda', 'CBZ': 'Yamaha'}
Dictionary after removing last item:
{'bullet': 'Royal Enfield', 'apache': 'TVS', 'hornet': 'Honda'}

Using del keyword

We know that we use the del keyword to delete any Python object. In the case of dictionary also we can delete an item using del keyword. We simply need to access the item using its key and delete it using del. For example,

bikes = {
    'bullet': 'Royal Enfield',
    'apache': 'TVS',
    'pulsar': 'Bajaj',
    'hornet': 'Honda'
}
print("Original dictionary:")
print(bikes)

#deleting element with key 'apache'
del bikes['apache']
print("Dictionary after deleting item with key 'apache':")
print(bikes)


Output:

Original dictionary:
{'bullet': 'Royal Enfield', 'apache': 'TVS', 'pulsar': 'Bajaj', 'hornet': 'Honda'}
Dictionary after deleting item with key 'apache':
{'bullet': 'Royal Enfield', 'pulsar': 'Bajaj', 'hornet': 'Honda'}

Using clear() method

We use clear() method to remove all the items from the dictionary. This method is used to empty the dictionary. For example,

bikes = {
    'bullet': 'Royal Enfield',
    'apache': 'TVS',
    'pulsar': 'Bajaj',
    'hornet': 'Honda'
}
print("Original dictionary:")
print(bikes)

#removing all items of the dictionary
bikes.clear()
print("Dictionary after using clear():", bikes)

Output:

Original dictionary:
{'bullet': 'Royal Enfield', 'apache': 'TVS', 'pulsar': 'Bajaj', 'hornet': 'Honda'}
Dictionary after using clear(): {}

Properties of a Python Dictionary

Mutability

Python dictionary is mutable. That means we can add, modify or delete items from a dictionary any time and any number of times. We have already seen several methods to add and modify the dictionary.

Order of sequence

Traditionally Python dictionaries were unordered collection. But after Python version 3.7, dictionaries became somehow ordered. Python remembers the order in which items are placed inside a dictionary. However, this order does not matter as we still cannot access dictionary items with their index.

No Duplicates

Python dictionaries do not support duplicate items. This is because the items of a dictionary are in key-value format and all the keys should be unique. It may be possible that two or more keys correspond to the same value but all keys must be distinct.

Data type of dictionary items

We know that dictionary items are key-value pairs. Here, each key can be any python object of primitive data type (integer, float, or string) or an immutable sequence(tuple) but it cannot be a mutable sequence. Whereas, values can be anything. It can be of primitive type or it could be any sequence (lists, tuple, or dictionary). For example,

mydict = {
    'model': 'DX900Cf',
    'brand': 'Tesla',
    'displacement': 1600,
    'fuel capacity': 29.5,
    'colors': ['red', 'black', 'silver'],
    'electric': True 
}
print(type(mydict))
print(mydict)

Output:

<class 'dict'>
{'model': 'DX900Cf', 'brand': 'Tesla', 'displacement': 1600, 'fuel capacity': 29.5, 'colors': ['red', 'black', 'silver'], 'electric': True}

Length of dictionary

The length of a dictionary determines the number of items present inside the dictionary. We can determine the length of the dictionary using len() method. For example,

mydict = {
    'one': 'first',
    'two': 'second', 
    'three': 'third',
    'four': 'fourth'
}

#length of dictionary
print("Length of dictionary:", len(mydict))

Output:

Length of dictionary: 4

What operations can be done on Python dictionaries?

Python dictionaries do not support Concatenation and Repetition. However, we can perform Iteration and Membership operations on dictionaries.

Iteration

Iteration refers to iterating over all the items of the dictionary. We use for loop to iterate through a dictionary. We can iterate over a dictionary in three ways.

I. Iterating through keys

By default, when we iterate through a dictionary it returns the keys of all the items. However, we can also explicitly use keys() method to retrieve all the keys. For example,

result = {
    'Physics': 93.75,
    'Chemistry': 89,
    'Maths': 96.5,
    'Computer Science': 92.25
}

#iterating through keys of the dictionary
for subject in result:
    print(subject)


#using keys method
print("\nIteration using keys() method:")
for subject in result.keys():
    print(subject)

Output:

Physics
Chemistry
Maths
Computer Science

Iteration using keys() method:
Physics
Chemistry
Maths
Computer Science

II. Iterating through values

To iterate through the values of all the items of the dictionary we can use keys as indexes. In addition, we also have values() method to directly iterate over all the values. For example,

result = {
    'Physics': 93.75,
    'Chemistry': 89,
    'Maths': 96.5,
    'Computer Science': 92.25
}

#iterating through values of the dictionary
for subject in result:
    print(result[subject])

#iterating through values using values() method
print("\nIteration using values() method:")
for marks in result.values():
    print(marks)

Output:

93.75
89
96.5
92.25

Iteration using values() method:
93.75
89
96.5
92.25

III. Iterating through both keys and values

Apart from the above two ways, we can also iterate through both keys and values simultaneously. For this, we need to use items() method. This method returns the key-value pair as a tuple of two elements. For example,

result = {
    'Physics': 93.75,
    'Chemistry': 89,
    'Maths': 96.5,
    'Computer Science': 92.25
}

#iterating through items of dictionary
for item in result.items():
    print(item)

Output:

('Physics', 93.75)
('Chemistry', 89)
('Maths', 96.5)
('Computer Science', 92.25)

Membership

Membership operation determines whether a key is present inside a dictionary. It can only check for keys and not for values. It can be determined using the membership (in) operator. For example,

veggies = {
    'spinach': 'green',
    'tomato': 'red',
    'carrot': 'red',
    'potato': 'brown'
}

#checking for 'carrot' in dictionary
print("'carrot' is member of veggies:")
print('carrot' in veggies)

#checking for 'onion' in dictionary
print("'onion' is member of veggies:")
print('onion' in veggies)

Output:

'carrot' is member of veggies:
True
'onion' is member of veggies:
False

Python Dictionary methods

Python has various built-in methods for Dictionaries. We have already used some of them in previous sections of the article.

MethodDescription
clear()As we have already seen this method removes all the items from the dictionary
copy()This method is used to get a copy of the specified Python dictionary
fromkeys(keys, value)This method creates a dictionary with specified keys where each key is assigned the same value. By default value will be none
get()As we have already seen this method is used to retrieve value associated with the specified key
items()As we have already seen this method returns the items of the dictionary as a list of tuples
keys()As we have already seen this method returns a list containing all the keys of the dictionary
pop(key)As we have already seen this method removes the item with the specific key from the dictionary
popitem()As we have already seen this method removes the last inserted key-value pair
setdefault(key, value)This method returns the value of the item with the specified key. If the key does not exist, it inserts the key, with the specified value
update(iterable)As we have already seen this method updates the dictionary with provided iterable
values()As we have already seen this method returns a list containing all the values of the dictionary

Conclusion

In this article, we have read about creating Python dictionaries, accessing their items, adding, modifying, and removing items from the dictionary. We have also read about important properties of the Python dictionaries, iteration, and dictionary methods.

Piyush Sharma

Third-year computer engineering student inclined towards the latest trends and technology. Always keen to explore and ready to learn new things. To read more articles on Python, stay tuned to avidpython.com.

Leave a Reply