Different Ways to Create a Dictionary in Python

Dictionary in Python is a very important data-structure which can have unordered list of key value pairs.
See a dictionary
d={2:4, 3:9, 4:16, ‘India’:’Delhi’}
In dictionary d, you can key:value pairs this is one of the ways to create a dictionary. However, there are several ways to create a dictionary using dict() function.

In this post, I will demonstrate different ways to create a dictionary in Python.Dictionary-in-Python

1- Using name and value pairs inside dict() function

d=dict(India=’Delhi’, Japan=’Tokyo’, Spain=’Madrid’)
Here name is of string type and is only a variable, and will not be in single or double quotes.

2- key:value pairs inside dict() function
d=dict({‘India’:’Delhi’, ‘Japan’:’Tokyo’, ‘Spain’:’Madrid’})

3- Using zip() function inside dict() function

d=dict(zip((‘India’, ‘Japan’, ‘Spain’), (‘Delhi’, ‘Tokyo’, ‘Madrid’)))

4- Key value pairs in the form of lists and tuples

4.1-Using lists
d=([[‘India’, ‘Delhi’], [‘Japan’, ‘Tokyo’], [‘Spain’, ‘Madrid’]])
4.2 Using tuples

d=(((‘India’, ‘Delhi’), (‘Japan’, ‘Tokyo’), (‘Spain’, ‘Madrid’)))

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

©Postnetwork-All rights reserved.