Dictionaries in Python

Pallavi Dhotre

6 months ago

Dictionaries in Python | insideAIML
Table of Content
Introduction
Python Dictionaries
  • Python create dictionary
  • How to Get Values from python dictionaries?
Python Dictionary Methods
  • clear()
  • copy()
  • fromkeys()
  • get()
  • items()
  • pop()
  • popitem()
  • keys()
  • values()
  • update()
Create a list of dictionaries python
Python Create dictionary from list
How are python dictionaries different from python lists?
Summary

Introduction

          Do you know how are python dictionaries different from python lists? and how we can handle the dictionaries? In this article, we will go deeper into python dictionaries and we also discuss methods of python dictionaries, the difference between dictionaries and lists, create a list of dictionaries and create a dictionary from lists with examples. 

Python Dictionaries

          Another popular data structure used in python is dictionaries, similar to lists. In python dictionaries, the elements are stored in the form of key-value pairs. Since all data does not exist in the tabular form, the flexibility of the structure is offered by a dictionary. In real life, a dictionary is not a collection of similar data – from one object we can access different values. e.g. telephone directory, from the name of the person we can access their phone number and address. In python dictionaries, keys play an important role because we can access the element using keys. 
A dictionary can have multiple key-value pairs. A key-value pair is written as Key: value where ':' is a separator. Keys can have the following data types: integer, real, string, char, and values can be of any type. In other terms, each item in the dictionary is added as a key-value pair.

Python create dictionary 

          To create python dictionaries we use key-value pairs. Keys are separated from their values by a colon( : ), a comma is used as an element separator. Everything in python dictionaries is enclosed within curly brackets { }.
# python dictionary example
demo_dict={} #creating empty dictionary
demo_dict={'name':'Mariya','age':25,'Country':'India'} #create dictionary in python 3
print(demo_dict)
Output
{'name': 'Mariya', 'age': 25, 'Country': 'India'}

How to Get Values from python dictionaries?

          Dictionaries are a set of key-value pairs, we can use keys as an index to access the element from the dictionary. However, if the key does not exist then the program will throw an error. Let’s see how to access the elements from the dictionary using python dictionary keys :
# python dictionary example
demo_dict={'name':'Mariya','age':25,'Country':'India'} #create dictionary in python 3
# accessing the elements of dictionary using python dictionary keys
print(demo_dict['name']) # name is a key and Mariya is a value
print(demo_dict['age']) # age is a key and 25 is a value
print(demo_dict['Country']) # Country is a key and India is a value
Output:
Mariya

25

India

Python Dictionary Methods

          There are several built-in python dictionary methods we will see one by one:

clear()

          In python dictionaries, the clear() method is used to remove all the elements from the dictionary given in the program.
demo_dict={'name':'Mariya','age':25,'Country':'India'} #create dictionary in python 3
print(demo_dict) #before clear() method
demo_dict.clear() #using clear() method
print(demo_dict) #after using clear() method
output
{'name': 'Mariya', 'age': 25, 'Country': 'India'}

{}

copy()

          copy() method is used to return the copies of the given python dictionaries. 
See the following code:
demo_dict={'name':'Mariya','age':25,'Country':'India'} #create dictionary in python 3
x=demo_dict.copy() #creating copy of the dictionary
print(x)
Output
{'name': 'Mariya', 'age': 25, 'Country': 'India'}

fromkeys()

          In python dictionaries, a fromkeys() function returns a dictionary with a specific key: value pair.
demo_dict={'name':'Mariya','age':25,'Country':'India','Hobby':'Sports'} #create dictionary in python 3
x=demo_dict.fromkeys(['age'],25) #accessing specific element
print(x)
output
{'age': 25}

get()

          The get() function returns the value of a specific key in the dictionary.
demo_dict={'name':'Mariya','age':25,'Country':'India','Hobby':'Sports'} #create dictionary in python 3
x=demo_dict.get('name') #accessing specific element
print(x)
Output
Mariya

items()

          This method changes the view of dictionary items and returns them as a tuple. Example Code is given below
demo_dict={'name':'Mariya','age':25,'Country':'India','Hobby':'Sports'} #create dictionary
x=demo_dict.items() #view the elements in dictionary as a tuple
print(x)
Output
dict_items([('name', 'Mariya'), ('age', 25), ('Country', 'India'), ('Hobby', 'Sports')])

pop()

          This method removes the specific object from the dictionary. Example code is given below
demo_dict={'name':'Mariya','age':25,'Country':'India','Hobby':'Sports'} #create dictionary
print(demo_dict) # before removing the item
demo_dict.pop('Hobby')
print(demo_dict) #after removing the item
Output
{'name': 'Mariya', 'age': 25, 'Country': 'India', 'Hobby': 'Sports'}

{'name': 'Mariya', 'age': 25, 'Country': 'India'}

popitem()

          This method removes the elements in the dictionary which is inserted at the end. Let’s see the code given below
demo_dict={'name':'Mariya','age':25,'Country':'India','Hobby':'Sports'} #create dictionary
print(demo_dict) # before removing the item
demo_dict.popitem()
print(demo_dict) #after removing the item
Output
{'name': 'Mariya', 'age': 25, 'Country': 'India', 'Hobby': 'Sports'}

{'name': 'Mariya', 'age': 25, 'Country': 'India'}

keys()

          The list of keys used in the dictionary is returned by this method. Example code is given below
demo_dict={'name':'Mariya','age':25,'Country':'India','Hobby':'Sports'} #create dictionary
print(demo_dict.keys()) #return keys
output
dict_keys(['name', 'age', 'Country', 'Hobby'])

values()

          This method returns the list of values associated with keys used in the dictionary. Example code is given below
demo_dict={'name':'Mariya','age':25,'Country':'India','Hobby':'Sports'} #create dictionary
print(demo_dict.values()) #return values
Output
dict_values(['Mariya', 25, 'India', 'Sports'])

update()

          This method is used to insert the new key: value pair to the dictionary.
demo_dict={'name':'Mariya','age':25,'Country':'India','Hobby':'Sports'} #create dictionary
print(demo_dict) #without update()
demo_dict.update({'1':111})
print(demo_dict) #after update()
Output
{'name': 'Mariya', 'age': 25, 'Country': 'India', 'Hobby': 'Sports'}

{'name': 'Mariya', 'age': 25, 'Country': 'India', 'Hobby': 'Sports', '1': 111}

Create a list of dictionaries python

          Using the following approach we can create a list of dictionaries in python.
demo_list=[{'name':'Mariya','age':25},{'Country':'India','Hobby':'Sports'}] #create a list of dictionaries python
print(demo_list)
#access the elements from the list of dictionary
print(demo_list[0]['age']) # this will return 25
print(demo_list[1]['Country']) # this will return India
Output:
[{'name': 'Mariya', 'age': 25}, {'Country': 'India', 'Hobby': 'Sports'}]

25

India

Python Create dictionary from the list

          We can create a dictionary from the list in python using three approaches. Let’s look into a brief example:
books=['history','maths','science'] #create a list
#first approach python create dictionary from list
books_dict=dict.fromkeys(books,'available') #create dictionary from list using fromkeys() method
print(books_dict)
#second approach python create dictionary from list
books_dict1={books:'should study'for books in books} #create dictionary from list using dictionary comprehension
print(books_dict1)
#third approach python create dictionary from list
price=[250,450,670]
books_dict2=dict(zip(books,price)) #create dictionary from list using zip()
print(books_dict2)
Output
{'history': 'available', 'maths': 'available', 'science': 'available'}

{'history': 'should study', 'maths': 'should study', 'science': 'should study'}

{'history': 250, 'maths': 450, 'science': 670}

How are python dictionaries different from python lists?

Difference between dictionaries and lists | insideAIML

Summary

          In this article we discussed python dictionaries, python dictionary methods, create a list of dictionaries in python, python create a dictionary from the list, and the difference between python dictionaries and python lists. Dictionaries are set of key: value pairs separated by ‘:’ and each element in a dictionary is separated by a comma. Dictionaries are unordered and mutable. Elements of the dictionaries can be accessed using keys. We hope you enjoyed the article. If you have any doubts regarding this article, feel free to ask in the comment section below. 
     
Enjoyed reading this blog? Then why not share it with others. Help us make this AI community stronger. 
To learn more about such concepts related to Artificial Intelligence, visit our blog page.
You can also ask direct queries related to Artificial Intelligence, Deep Learning, Data Science and Machine Learning on our live discussion forum.
Keep Learning. Keep Growing. 
           

Submit Review