Dictionary In Python

Python Dictionary

The English word for this term is a list of items of data or words. In reference to information retrieval or word processing.

A dictionary is a collection of keys and values. These key and value pairs are used to store specific information, where the value points its data inside the key. Let’s look into an example. Google and Amazon are the keys and the services they provide is the values.

company = {
“Google”: [“Search Engine”,”Cloud Storage”,”Firebase”,”Tenorflow”,”GPay”]
“Amazon”:[“Online Shopping”,”Amazon Pay”,”Alexa”,”AWS”]

In the above example company is the dictionary, Google and Amazon are the keys and the service list is the values. Key is a holder that holds a value, here is the syntax:

variable_name = {key1:value1,key2:value3,keyN:valueN}

Dictionary is enclosed within {} curly brackets. If you need to represent String value then it should be enclosed within double quotes, the same goes for the key as well. The combination of Key and Value is known as Item.

>>> ceo = {"Google":"Sundar Pichai","Microsoft":"Satya Nadella","Adobe":"Shantanu Narayen","Tesla":"Elon Musk","Apple":"Tim Cook","Facebook":"Mark Zuckerberg"}
>>> ceo
{'Google': 'Sundar Pichai', 'Microsoft': 'Satya Nadella', 'Adobe': 'Shantanu Narayen', 'Tesla': 'Elon Musk', 'Apple': 'Tim Cook', 'Facebook': 'Mark Zuckerberg'}
<class 'dict'>
>>> ceo['Google']
'Sundar Pichai'
>>> ceo['Tesla']
'Elon Musk'
>>> ceo['Apple']
'Tim Cook'
>>> ceo['Amazon'] #there is no key named Amazon
KeyError: 'Amazon'

In the above example, CEO is the variable name and the name of the Companies are dictionary keys. These keys hold the values that are the name of the CEO of the respective Company(key). In order to get the CEO name of the company, you need to declare the key name within square brackets. If the Company name is not in the Dictionary it will execute KeyError, which means the name/key is not declared.

Add A New Entry In Dictionary

Consider the same CEO example. Let us add the Amazon CEO name to the list.

>>> len(ceo) #previous length of the ceo dictionary.
>>> ceo['Amazon']="Andy Jassy"
>>> len(ceo)
>>> ceo['Amazon']
'Andy Jassy'

Dictionary Method Operations: The Concept where you are already familiar

>>> genre = {'Adventure': 'One Piece', 'Shounen': 'Hunter X Hunter', 'Action': 'Naruto', 'Crime': 'Death Note', 'Romance': 'Wotakoi', 'Comedy': 'Gintama', 'Fantasy': 'Attack On Titan', 'Slice of Life': 'Mushishi'}
>>> genre
{'Adventure': 'One Piece', 'Shounen': 'Hunter X Hunter', 'Action': 'Naruto', 'Crime': 'Death Note', 'Romance': 'Wotakoi', 'Comedy': 'Gintama', 'Fantasy': 'Attack On Titan', 'Slice of Life': 'Mushishi'}

With help of a genre dictionary, let us work on some methods.


The syntax of length is the same for all Data types.

>>> len(genre)

Next up, insert a new element i.e., an item in Dictionary. Item is a Key-Value pair.

We already have a total of 8 lengths of Genre dictionary, add one more item in the genre dictionary. Unfortunately, we don’t have any built-in insert function but we already know how to add the new items.

>>> genre['Sci-Fi']="Steins Gate"
>>> genre['Sports']="Hajime No Ippo"
>>> len(genre)
>>> genre
{'Adventure': 'One Piece', 'Shounen': 'Hunter X Hunter', 'Action': 'Naruto', 'Crime': 'Death Note', 'Romance': 'Wotakoi', 'Comedy': 'Gintama', 'Fantasy': 'Attack On Titan', 'Slice of Life': 'Mushishi', 'Sci-Fi': 'Steins Gate', 'Sports': 'Hajime No Ippo'}
>>> genre[1] #dictionary doesn’t return the index.
KeyError: 1

Note: You can’t slice the dictionary.

TypeError: unhashable type: 'slice'

The basic syntax to add new item inside the dictionary is: var_name[key_name] = value_name.


>>> len(genre)
>>> del genre['Crime']
>>> len(genre)
>>> del genre['Romance']
>>> genre['Romance']
KeyError: 'Romance'
>>> len(genre)
>>> del genre
>>> genre
NameError: name 'genre' is not defined

in and not in

in and not in concept in Dictionary is complete Jackpot. You can utilize this topic amazingly


>>> specifications = {"HP":["4GB RAM","1Tb HDD"],"DELL":["4GB RAM","256GB SSD"],"Lenevo":["8GB RAM","512GB SSD"],"HP2":["8GB RAM","1TB HDD","2GB Graphics Card"]}
>>> 'HP' in specifications
>>> 'Acer' in specifications
>>> '8GB RAM' in specifications['HP']
>>> '8GB RAM' in specifications['HP2']
>>> "4GB Graphics Card" in specifications['HP2']
>>> "2GB Graphics Card" in specifications['HP2']

not in

>>>'Apple' not in specifications
>>>"16GB RAM" not in specifications["DELL"]

Remember that in and not in only returns the output in Boolean Data Type.

Dictionary Operations

1. keys()

Keys are the holders of the dictionary, it is used as the index in the dictionary. keys() method returns all the keys from the dictionary. The return type is dictionary keys. You can check by running type(var_name.keys()), where var_name is a dictionary.

>>> genre.keys()
dict_keys(['Adventure', 'Shounen', 'Action', 'Crime', 'Romance', 'Comedy', 'Fantasy', 'Slice of Life', 'Sci-Fi', 'Sports'])

Let’s take a new example

>>> languages = {"Python":"Machine Learning","Java":"Android","JavaScript":"Web Development","C":"Embedded Systems"}
>>> languages.keys()
dict_keys(['Python', 'Java', 'JavaScript', 'C'])
for key in languages.keys():
… print(key)
>>> straw_hat = {"Captain":"Monkey D Luffy","Vice Captain":"Roronoa Zoro","Navigator":"Nami","Chef":"Sanji","Sniper":"Usopp","Doctor":"Chopper"}
>>> straw_hat.keys()
dict_keys(['Captain', 'Vice Captain', 'Navigator', 'Chef', 'Sniper', 'Doctor'])
for pirates in straw_hat.keys():
… print(pirates)
Vice Captain

2. values()

While discussing variables you might have heard of values over there for the first time. Values are the data that is stored inside a variable name. In Dictionary the task done by values is the same, we store the data of the key. Every Key in Dictionary must have a value. The return type of values() is dictionary_values. Let’s consider the same example dictionaries which are already declared.

>>> languages.values()
dict_values(['Machine Learning', 'Android', 'Web Development', 'Embedded Systems'])
>>> for value in languages.values():
… print(value)
Machine Learning
Web Development
Embedded Systems
straw_hat = {"Captain":"Monkey D Luffy","Vice Captain":"Roronoa Zoro","Navigator":"Nami","Chef":"Sanji","Sniper":"Usopp","Doctor":"Chopper"}
dict_values(['Monkey D Luffy', 'Roronoa Zoro', 'Nami', 'Sanji', 'Usopp', 'Chopper'])
>>> for pirates in straw_hat.values():
… print(pirates)
Monkey D Luffy
Roronoa Zoro

3. items()

Keys and Values together form Items. Items split the key-value pair into a Tuple and you can iterate these items by providing two variables. See the difference What happens when you provide two variables, likewise in single variables.

>>> languages.items()
dict_items([('Python', 'Machine Learning'), ('Java', 'Android'), ('JavaScript', 'Web Development'), ('C', 'Embedded Systems')])
for item in languages.items():
… print(item)
('Python', 'Machine Learning')
('Java', 'Android')
('JavaScript', 'Web Development')
('C', 'Embedded Systems')
for key,value in languages.items():
… print("{}:{}".format(key,value))
Python:Machine Learning
JavaScript:Web Development
C:Embedded Systems

Note: The attributes keys(), values(), and items() takes no argument.

4. get()

Recall the error: KeyError why do you think it occurs? Obviously a silly question. Using the get() method we can handle KeyError in the Pro way. First, let’s purposely get into KeyError. Consider the language example:

>>> languages = {"Python":"Machine Learning","Java":"Android","Javascript":"Web Development","C":"Embedded Systems"}
>>> languages['Python']
'Machine Learning'
>>> languages['C++']
KeyError: 'C++'

We have no Key with the name C++. Let’s deal with errors using get().

var_name = {items} #items = key:value
>>> languages.get("Python")
'Machine Learning'
>>> print(languages.get("C++"))

Second Method to deal with getting ()

>>> languages.get("C++","Sorry, not avaiable")
'Sorry, not avaiable'
>>> languages.get("Java","Sorry, not avaiable")

get(), will return None if the key is not found. If in case you provide any second argument then get() will return the second argument if the key is not found. It is None by default. Since this is new to you and a very useful command, it is good to have more examples.

>>> basket = {"apple":12,"kiwi":5,"watermelon":2,"graphes":25}
>>> basket.get("apple",0)
>>> basket.get("bananas",0)
>>> basket.get("kiwi",0)

In get method, it is compulsory to provide the first argument. But the second argument comes very handily on how you deal with those keys that are not found in the Dictionary.

5. pop()

>>> languages = {"Python":"Machine Learning","Java":"Android","JavaScript":"Web Development","C":"Embedded Systems"}
>>> len(languages)
>>> python_use = languages.pop("Python")
>>> python_use
'Machine Learning'
>>> languages
{'Java': 'Android', 'JavaScript': 'Web Development', 'C': 'Embedded Systems'}
>>> len(languages)

Recalling the Stack operation where elements are inserted and added from the same position that is TOP, whose index is -1. In Dictionary as well, we get to perform this pop operation in order to retrieve the last item from the dictionary. Once you perform the pop operation on the Dictionary the original dictionary length will be decremented by 1, as we have retrieved the TOP item i.e., the last item.

6. setdefault()

Consider this scenario before understanding setdefault() method. We have a Dictionary of CEO. But once assigned a value inside a key we can change it as Dictionary are Mutable. What if

var_name = {}
>>> birthdays = {}
>>> birthdays.setdefault("Luffy","May 5")
'May 5'
>>> birthdays.setdefault("Naruto","Oct 10")
'Oct 10'
{'Luffy': 'May 5', 'Naruto': 'Oct 10'}

If Key already exists, then the return value of the existing key will be returned.

>>> birthdays.setdefault("Luffy","Jan 10")
'May 5'
>>> birthdays
{'Luffy': 'May 5', 'Naruto': 'Oct 10'} #the key value is unaltered

The setdefault() method is the best way to ensure that a key exists in a dictionary or not.

7. clear()

var_name = {items}
>>> languages = {"Python":"Machine Learning","Java":"Android","Javascript":"Web Development","C":"Embedded Systems"}
>>> languages.clear()
>>> languages

clear erases all the Dictionary items and returns an empty dictionary. And clear() takes no argument which means you no need to specify anything within the parenthesis. Sometimes in large programs when you have multiple dictionaries, there are chances of overriding the same dictionary, in order to ensure if the dictionary is clean, you use a clear method.

Dictionaries Are Mutable

Just like Lists, dictionaries are mutable in Python. which means you can modify the assigned dictionary. In the below example you can notice the difference where the GUI application(value) was assigned to Python(key) initially and later the same key is modified with a new value.

>>> coding_use = {"Python":"GUI Application","Java":"Android Development","JavaScript":"Web App","Swift":"IOS","C++":"Game Development"}
>>> coding_use
{'Python': 'GUI Application', 'Java': 'Android Development', 'JavaScript': 'Web App', 'Swift': 'IOS', 'C++': 'Game Development'}
>>> coding_use["Python"]="Deep Learning"
>>> coding_use
{'Python': 'Deep Learning', 'Java': 'Android Development', 'JavaScript': 'Web App', 'Swift': 'IOS', 'C++': 'Game Development'}
>>> coding_use["JavaScript"]="Website"
>>> coding_use
{'Python': 'Deep Learning', 'Java': 'Android Development', 'JavaScript': 'Website', 'Swift': 'IOS', 'C++': 'Game Development'}


You can try 30 Days Python Programming by solving amazing code daily. Anime Vyuh Github Organization has a public repo, which will help you with 30 Days Of Python.

Check Out The Previous Tutorials Part On Learn Python.

If you like our content, support us by Buying a Coffee.