Code Pumpkin

Dictionaries in Python

October 28, 2018
Posted by Dipen Adroja

We have seen, list/sequences in the previous article. In this article, we will learn about Dictionaries in Python. If you are familiar with other languages then you can think of dictionaries as Map or hash tables. The python dictionary is an unordered collection of items having key: value pair.

We will see:

How to create a Dictionary?

We can create a dictionary by simply putting elements in {} separated by commas. Elements will have key: value pair. In Dictionary, values can be of any datatype and can repeat while keys should be unique and of type immutable.

Below is some of the way of creating a dictionary:

# creating empty dictionary
demo_dict = {}

# creating dictionary with integer keys
demo_dict = {1: 'code', 2: 'pumpkin'}

# creating dictionary with mixed keys
demo_dict = {'name': 'Dipen', 1: [1, 2, 4, 3]}

# using dict() built-in dict constroctor
demo_dict = dict( {1: 'code', 2: 'pumpkin'})

# from sequence/list having each item as a pair
demo_dict = dict([(1,'code'), (2,'pumpkin')])

How to access the Dictionary element?

Elements of a dictionary cannot be accessed using indexes. To access an element of a dictionary one can use key inside square brackets or using the get() methods.

The difference while using get() is that it returns None instead of KeyError if the key is not found.

demo_dict = {'name':'Pumpkin', 'experience': 27}

# Output: Pumpkin

# Output: 27
# this will return null
print('This is my value',demo_dict.get('address'))
# Trying to access keys which doesn't exist throws error




('This is my value', None)

Traceback (most recent call last):

  File "", line 11, in <module>


KeyError: 'address'

How to modify a Dictionary?

Dictionaries are mutable objects. We can add new elements and or change the value of the existing element. If the key present then that particular element gets updated else new element will be added. We can remove a particular element in a dictionary by using the method pop() which removes an element with the provided key and returns the value. clear() method can be used to clean the complete dictionary.  We can also use the del keyword to remove individual items or the entire dictionary itself.

demo_dict = {'name':'Pumpkin', 'experience': 27, 'category': 'vip'}

# Update value
demo_dict['name'] = "CodePumpkin"

demo_dict['age'] = 40

# remove particular element from dict

# delete a particular element
del demo_dict['category']

# remove all elements from dicts


{'category': 'vip', 'name': 'CodePumpkin', 'experience': 27}

{'category': 'vip', 'age': 40, 'name': 'CodePumpkin', 'experience': 27}


{'age': 40, 'name': 'CodePumpkin'}


Dictionary Methods

Below is the list of the methods available for the dictionary. 

Method Description
clear() Remove all elements from the dictionary.
copy() Return a shallow copy of the dictionary.
fromkeys(seq[,v]) Return a new dictionary with keys from seq and value equal to v(defaults to None).
get(key[,d]) Return the value of key. If the key doesn't exist, return d (defaults to None).
items() Return a new view of the dictionary's items (key, value).
keys() Return a new view of the dictionary's keys.
pop(key[,d]) Remove the item with the key and return its value or d if the key is not found. If d is not provided and the key is not found, raises KeyError
popitem() Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty.
setdefault(key[,d]) If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None).
update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys.
values() Return a new view of the dictionary's values

Dictionary Built-in Functions

Below is list of function which are commonly used.

Function Description
all() Return True if all keys of the dictionary are true (or if the dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.
len() Return the length (the number of items) in the dictionary.
cmp() Compares items of two dictionaries.

Return a new sorted list of keys in the dictionary.

Dictionary Comprehension

We can create a new dictionary from the iterable in Python. The syntax for the same is as below:

demo_dict = {i : i * 2 for i in range(10)}

Comprehension is one of the elegant ways of creating the dictionary. Along with for loop we can also add if statement to filter from iterable elements.

That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.

Happy Learning 🙂

If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.

We may not get time to plant a tree, but we can definitely donate ₹42 per Tree.

About the Author

Coder, Blogger, Wanderer, Philosopher, Curious pumpkin


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
For more information on supported HTML tags in disqus comment, click here.
Total Posts : 124
follow us in feedly

Like Us On Facebook