Python : 6 Different ways to create Dictionaries

In this article, we will discuss different ways to create dictionary objects in python.

What is a dictionary?

dictionary is an associative container that contains the items in key/value pairs.  For example, we if want to track the words and their frequency count in an article like,

“Hello” occurs 7 times
“hi” occurs 10 times
“there” occurs 45 times
“at” occurs 23 times
“this” occurs 77 times

We can use the python dictionary to keep this data, where the key will the string word and value is the frequency count.

Now let’s see different ways to create a dictionary,

Creating Empty Dictionary

We can create an empty dictionary in 2 ways i.e.

'''
Creating empty Dictionary
'''
# Creating an empty dict using empty brackets
wordFrequency = {}

# Creating an empty dict using dict()
wordFrequency = dict()

It will create an empty dictionary like this,

{}

Creating Dictionaries with literals

We can create a dictionary by passing key-value pairs literals i.e.

'''
Creating Dictionaries with literals
'''                                  
wordFrequency = {
    "Hello" : 7,
    "hi" : 10,
    "there" : 45,
    "at" : 23,
    "this" : 77
    }

It will create a dictionary like this,

{'this': 77, 'there': 45, 'hi': 10, 'at': 23, 'Hello': 7}

Creating Dictionaries by passing parameters in dict constructor

We can create a dictionary by passing key-value pairs in dictionary constructor i.e.

'''
Creating Dictionaries by passing parametrs in dict constructor
'''
wordFrequency = dict(Hello =  7, 
                     hi    = 10,
                     there  = 45,
                     at    = 23,
                     this  = 77
                     )

It will create a dictionary like this,

{'there': 45, 'hi': 10, 'this': 77, 'at': 23, 'Hello': 7}

Creating Dictionaries by a list of tuples

Suppose we have a list of tuples i.e.

# List of tuples    
listofTuples = [("Hello" , 7), ("hi" , 10), ("there" , 45),("at" , 23),("this" , 77)]

We can create a dict out of this list of tuple easily by passing it in constructor i.e.

# Creating and initializing a dict by tuple
wordFrequency = dict(listofTuples)

It will create a dictionary like this,

{'this': 77, 'there': 45, 'hi': 10, 'at': 23, 'Hello': 7}

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

Suppose we have a list of string i.e.

listofStrings = ["Hello", "hi", "there", "at", "this"]

Now we want to create a dictionary where all the elements of the above list will be keys and their default value is 0.
We can do that using fromkeys() function of dict i.e.

# create and Initialize a dictionary by this list elements as keys and with same value 0
wordFrequency = dict.fromkeys(listofStrings,0 )

It will Iterate over the list of string and for each element, it will create a key-value pair with value as default value provided and store them in dict.

It will create a dictionary like this,

{'this': 0, 'there': 0, 'hi': 0, 'at': 0, 'Hello': 0}

Creating a Dictionary by two lists

Suppose we have two lists i.e.

List of strings,

# List of strings
listofStrings = ["Hello", "hi", "there", "at", "this"]

List of integers,

# List of ints
listofInts = [7, 10, 45, 23, 77]

Now we want to use elements in the list of string as keys and items in the list of ints as value while creating a dictionary.
To do that we are going to use zip() function that will Iterate over the two lists in parallel.

For each entry in the list, it will create a key-value pair and finally create a zipped object. Now, we can pass this zipped object to dict() to create a dictionary out of it i.e.

# Merge the two lists to create a dictionary
wordFrequency = dict( zip(listofStrings,listofInts ))
# Merge the two lists to create a dictionary
wordFrequency = dict( zip(listofStrings,listofInts ))

It will create a dictionary like this,

{'this': 77, 'there': 45, 'hi': 10, 'at': 23, 'Hello': 7}

Python Dictionary Tutorial - Series:

  1. What is a Dictionary in Python & why do we need it?
  2. Creating Dictionaries in Python
  3. Iterating over dictionaries
  4. Check if a key exists in dictionary
  5. Check if a value exists in dictionary
  6. Get all the keys in Dictionary
  7. Get all the Values in a Dictionary
  8. Remove a key from Dictionary
  9. Add key/value pairs in Dictionary
  10. Find keys by value in Dictionary
  11. Filter a dictionary by conditions
  12. Print dictionary line by line
  13. Convert a list to dictionary
  14. Sort a Dictionary by key
  15. Sort a dictionary by value in descending or ascending order
  16. Dictionary: Shallow vs Deep Copy
  17. Remove keys while Iterating
  18. Get all keys with maximum value
  19. Merge two or more dictionaries in python

Subscribe with us to join a list of 2000+ programmers and get latest tips & tutorials at your inbox through our weekly newsletter.

The complete example is as follows,

def main():

    '''
    Creating empty Dictionary
    '''
    # Creating an empty dict using empty brackets
    wordFrequency = {}
    
    # Creating an empty dict using dict()
    wordFrequency = dict()
    
    print(wordFrequency)
    
    '''
    Creating Dictionaries with literals
    '''                                  
    wordFrequency = {
        "Hello" : 7,
        "hi" : 10,
        "there" : 45,
        "at" : 23,
        "this" : 77
        }
    
    print(wordFrequency)
    
 
    '''
    Creating Dictionaries by passing parametrs in dict constructor
    '''
    wordFrequency = dict(Hello =  7, 
                         hi    = 10,
                         there  = 45,
                         at    = 23,
                         this  = 77
                         )
    
    print(wordFrequency)
    
    
    '''
    Creating Dictionaries by a list of tuples
    '''

    # List of tuples    
    listofTuples = [("Hello" , 7), ("hi" , 10), ("there" , 45),("at" , 23),("this" , 77)]
    
    # Creating and initializing a dict by tuple
    wordFrequency = dict(listofTuples)
        
    print(wordFrequency)    
    
    
    '''
    Creating Dictionary by a list of keys and initialzing all with same value
    '''    
    
    listofStrings = ["Hello", "hi", "there", "at", "this"]
    
    # create and Initialize a dictionary by this list elements as keys and with same value 0
    
    wordFrequency = dict.fromkeys(listofStrings,0 )
        
    print(wordFrequency)

    '''
    Creating a Dictionary by a two lists
    '''         
    # List of strings
    listofStrings = ["Hello", "hi", "there", "at", "this"]
    
    # List of ints
    listofInts = [7, 10, 45, 23, 77]

    # Merge the two lists to create a dictionary
    wordFrequency = dict( zip(listofStrings,listofInts ))
    
    print(wordFrequency)

if __name__ == "__main__":
    main()

Output:

{}
{'hi': 10, 'there': 45, 'this': 77, 'at': 23, 'Hello': 7}
{'there': 45, 'hi': 10, 'this': 77, 'at': 23, 'Hello': 7}
{'hi': 10, 'there': 45, 'this': 77, 'at': 23, 'Hello': 7}
{'hi': 0, 'there': 0, 'this': 0, 'at': 0, 'Hello': 0}
{'hi': 10, 'there': 45, 'this': 77, 'at': 23, 'Hello': 7}

 

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top