What are Dictionaries in Python?

  • Dictionary in Python is an unordered collection of data values
  • Used to store data values like a map, which unlike other Data Types that hold only single value as an element,
  • Dictionary holds  key:value pair
DICTIONARY

6 Different ways to create Dictionaries:

1. Creating Empty Dictionary :

SYNTAX :

 dictname = { } or dictname = dict()

EXAMPLE :

2. Creating Dictionaries with literals :

SYNTAX :

dictname = {         
   key1 : value1,    
   key2 : value2,    
   key3 : value3, ...
  }                  

EXAMPLE :

3. Creating Dictionaries by passing parameters in dict constructor :

SYNTAX :

dictname = dict([(key1, value1), (key2, value2), (key3, value3), ...])

EXAMPLE :

4. Creating Dictionaries by a list of tuples :

SYNTAX :


listofTuplesName = [(Key1, value1), (key2, value2), (key3, value3), ...]
dictname = dict (listOfTuplesName)                                      

EXAMPLE :

5. Creating a Dictionary by a list of keys and initializing all with the same value :

SYNTAX :


listofStringsName = [key1, key2, key3, ...]       
dictname = dict.fromkeys (listofStringsName,value)

EXAMPLE :

6. Creating a Dictionary by two lists :

SYNTAX :


list1 = [value1, value2, value3, ...]
list2 = [key1, key2, key3, ...]      
dictname = dict( zip(list1, list2) ) 

EXAMPLE :

 

SOURCE ARTICLE : https://thispointer.com/python-6-different-ways-to-create-dictionaries/