Python dictionary initialize – Complete tutorial

In this Python tutorial, we will discuss the Python dictionary initialize. Here we will also cover the below examples:

  • Python dictionary initialize empty
  • Python dictionary initialize to 0
  • Python dictionary initialize with none value
  • Python dictionary initialize with values
  • Python dictionary initialize with empty list
  • Python dictionary initialize if empty
  • Python initialize dictionary with keys and values
  • Python initialize dictionary with for loop
  • Python initialize dictionary with multiple Keys
  • Python initialize dictionary with keys
  • Python initialize dictionary from string
  • Python initialize dictionary list comprehension

Python dictionary initialize

  • In Python, dictionaries are the unordered collection of items and it contains key and value pair so to create dictionaries we will use “curly braces”.
  • Initialization means the process of preparing something to start.
  • There are various method to initalize a dictionary in Python.
    • Using dict() constructor
    • Using setdefault() function
    • Using fromKeys() method
    • Using defaultdict() method
    • Using dict() and zip() method

Using dict() constructor to initialize dictionary in Python

  • Let us see how to initialize dictionary in Python by using dict() constructor.
  • The dict() constructor can initialize a dictionary by passing arguments in the form of key-value pair.

Example:

Let’s take an example and check how to initialize a dictionary in Python.

my_dict = dict(Austraila=200, Newyork=300, Srilanka=600)
print("Initialze Dictionary",my_dict)

In the above code First, we will create a tuple and pass parameter in the dict() constructor.

Here is the screenshot of the following given code

Python dictionary initialize
Python dictionary initialize

Using setdefault() function to initialize dictionary in Python

The setdefault() method returns the value of a key within a list comprehension.

Example:

my_dictionary = {} 
[my_dictionary.setdefault(i, []) for i in range(4)] 
   
my_dictionary[0].append('George') 
my_dictionary[1].append('John') 

print ("Initialize dictionary : " + str(dict(my_dictionary)))

Here is the Screenshot of the following given code

Python dictionary initialize by setdefault method
Python dictionary initialize by setdefault method

This is how to setdefault() function to initialize dictionary in Python.

Read Python Dictionary update with examples

Using fromKeys() method to initialize a dictionary in Python

The fromkeys() function can be used if you want to create all the keys in a dictionary with the same value, then we can easily use this method.

Example:

new_key = ["James", "Potter", "mathew"]

Ini_dic = dict.fromkeys(new_key, 0)
print("Dictionary Initialization",Ini_dic)

Here is the Screenshot of the following given code

Python dictionary initialize by fromkeys method
Python dictionary initialize by fromkeys method

This is how to fromKeys() method to initialize a dictionary in Python.

Using defaulltdict() method to initialize a dictionary in Python

The Python dictionary defaultdict() function can be used if the user provides a default value for the key that does not exist then it evaluates the operation and initializes Key-value elements.

Example:

from typing import DefaultDict

my_dictionary = DefaultDict(list)
my_dictionary[0].append('Kane') 
my_dictionary[1].append('Pollard') 
my_dictionary[2].append('Watson')
print ("Initialize dictionary : " + str(dict(my_dictionary)))

Here is the Screenshot of the following given code

Python dictionary initialize by defaultdict method
Python dictionary initialize by defaultdict method

This is how to use defaulltdict() method to initialize a dictionary in Python.

Read Python dictionary values to list

Using dict() and zip() method to initialize a dictionary in Python

The Python zip() function take one or more iterables like Python tuples and Python list. Then we have converted the tuples into dictionaries. In this example, we have to pass index[list] as an argument.

Example:

new_list = ["Australia", "Hong-Kong", "singapore"]

Ini_dict = dict(zip(new_list, [1]*len(new_list)))

print(Ini_dict)

Here is the screenshot of the following given code:

Python dictionary Initialize a dictionary by dict and zip method
Python dictionary Initialize a dictionary by dict and zip method

This is how to use dict() and zip() method to initialize a dictionary in Python.

Python dictionary initialize empty

  • Let us see how to initialize an empty Python dictionary by using open curly brackets symbol{}
  • The empty dictionary is also initialized by dict() built-in function without any parameters.

Example:

my_Dict = {}

print("Empty Dictionary",my_Dict)
print("Length of dictionary:", len(my_Dict))

Here is the Screenshot of the following given code

Python dictionary initialize empty
Python dictionary initialize empty

Read Python Dictionary sort

How to initialize an empty dictionary in Python

In this example, we can check how to create an empty dictionary in Python using the dict() function. Dict() function returns an object that stores key-value pairs of dictionaries. It is a built-in function in Python.

Example:

Dictionary = dict()
 
# print dictionary
print("Empty Dictionary",Dictionary)

Here is the Screenshot of the following given code

Python dictionary initialize by dict method
Python dictionary initialize by dict method

The above code, we can use to initialize an empty dictionary in Python.

Python dictionary Initialize to 0

  • Let us see how to initialize a Python dictionary value to 0 by using the fromkeys() method.
  • In this case, if the value argument is set=0 then all keys in the dictionary are set to the provided value.

Example:

my_dict =dict.fromkeys(['Mangoes','Oranges','cherry'],0)
print("Initialize value=",my_dict)
Python dictionary Initialize to 0
Python dictionary Initialize to 0

This is an example of a Python dictionary Initialize to 0.

Read Python Dictionary index

Python dictionary initialize with none values

  • Here we can check how to initialize a Python dictionary with none by using zip() and repeat() function.
  • In this example we can easily use these functions to perform this task.
  • Zip() function returns an iterator element of tuples based on the iterator items and the none value is combined with the keys. While in repeat() function we can easily give the number that how many times the value will be printed.

Example:

from itertools import repeat
  
output = dict(zip(range(5), repeat(None)))

print("Initialize dictionary with None values : " + str(output))

In the above code first, we will import an itertools library for the repeat() function and by using the zip()+repeat() function to get the none values.

Here is the Screenshot of the following given code

Python dictionary initialize with none value
Python dictionary initialize with none value

This is to initialize Python dictionary with none values.

How to initialize a dictionary with none value

Here we can easily use the fromkeys() function to create a dictionary with none value

Example:

my_dict = dict.fromkeys(['London', 'Paris','Germany','France'])
print("Initailze dictionary none:",my_dict)

Note: In this example, the dictionary takes by default value none by using the fromkeys() function.

Here is the Screenshot of the following given code

Python dictionary initialize with none value from keys
Python dictionary initialize with none value from keys

Python dictionary initialize with values

  • Let us see how to initialize a dictionary with values in Python.
  • In this example we can use if __name__ == ‘__main__’: and fromkeys() function.
  • So this is a built-in variable and it will return the name of the module. Each module contains one attribute called “_name” which will return the name of that module.

Example:

if __name__ == '__main__':
  my_dict = dict.fromkeys(['Chinese', 'Italian', 'Mexican','Thai'], [])
  my_dict.get('Chinese').append(1)
 
print(my_dict)

Here is the Screenshot of the following given code

Python dictionary initialize with values
Python dictionary initialize with values

How to initialize a dictionary with values

In this example, the default function can be used if the user provides a default value for the key that does not exist then it evaluates the operation and initializes Key-value elements.

Example:

from typing import DefaultDict

my_dict = DefaultDict(list)
my_dict[0].append('Peach') 
my_dict[1].append('lilly') 
my_dict[2].append('Rose')
print ("Initialize dictionary with values : " + str(dict(my_dict)))

Here is the Screenshot of the following given code

Python dictionary initialize with value by defaultdict method
Python dictionary initialize with value by defaultdict method

The above code, we can use to initialize a dictionary with values in Python.

Python dictionary initialize with empty list

  • Let us see how to initialize a dictionary with an empty list in Python.
  • By using dictionary comprehension first we declare the number of keys and then initialize the empty list.
  • In this example, we use an empty list as an argument and the range of elements that are required to the key to initialize a dictionary.

Example:

Let’s take an example and check how to initialize a dictionary with an empty list.

my_dictionary = {emp_list: [] for emp_list in range(3)}

print ("Initialize dictionary with empty list : " + str(my_dictionary))

Here is the Screenshot of the following given code

Python dictionary initialize with empty list
Python dictionary initialize with an empty list

Python dictionary initialize if empty

  • Here we can check if a Python dictionary is empty or not by using the len() function.
  • len() function will return the size or length of the given string. In this example, we set the parameter ==0 which means no string is available in the list.

Example:

Let’s take an example and check if the dictionary is empty

my_dict = {}

if len(my_dict) == 0:
    print (" Initialize Dictionary is Empty")

Here is the Screenshot of the following given code

Python dictionary initialize if empty
Python dictionary initialize if empty

Check If a Python dictionary is empty

  • By using the bool() function we can perform this task.
  • First, we will initialize a empty dictionary and pass an empty string in bool() function that will return a true, if dictionary is empty.

Example:

empt_dict = {}

Ini_dic = not bool(empt_dict)

print("Dictionary is empty : " + str(Ini_dic))

Here is the Screenshot of the following given code

Python dictionary initialize if empty bool method
Python dictionary initialize if empty bool method

This is how to check If a Python dictionary is empty.

Python initialize dictionary with keys and values

  • Let us discuss how to initialize a dictionary with keys and values.
  • In this example take two lists which are new_key and new_value that stores elements or values, following functions can be used to make a dictionary object.
  • By using the zip() function we can convert the list to the dictionary.

Example:

Let’s take an example and check how to initialize a dictionary with keys and values

new_key= ['m','n','o','p']
new_value= [4,6,7,9]
my_dict= dict(zip(new_key,new_value))
print(my_dict)

Here is the Screenshot of the following given code

Python dictionary initialize with keys and values
Python dictionary initialize with keys and values

The above Python code we can use to initialize with keys and values in Python.

Python initialize dictionary with for loop

  • Let us see how to initialize a dictionary with for loop method.

Example:

country = ["Malaysia", "Tokyo", "Russia"]
my_dic = { i: {} for i in country}
print(my_dic)

Here is the Screenshot of the following given code

Python initialize dictionary with for loop
Python initialize dictionary with for loop

This is how to initialize a dictionary with for loop in Python.

Python initialize dictionary with multiple keys

  • Let us see how to initialize a dictionary with multiple keys in Python.
  • In this example we can easily use the loop method to create a dictionary with multiple keys.

Example:

to_dict = {}

multi_keys = ['Jennifer', 'potter', 'bill']
  
for keys in multi_keys:
    to_dict[keys] = 3

print("Initialize dictionary multiple key-value : " + str(to_dict))

Here is the Screenshot of the following given code

Python initialize dictionary with multiple keys
Python initialize dictionary with multiple keys

Python initialize dictionary with keys

  • Let us see how to initialize a dictionary with keys in Python.
  • Use fromkeys() function to initialize a dictionary with keys
  • In this example, we can easily create a list with only keys elements by using list of keys as iterable to initialize a dictionary.

Example:

new_list = ["p", "q"]

my_dict = dict.fromkeys(new_list)
print(my_dict)

Here is the Screenshot of the following given code

Python initialize dictionary with keys
Python initialize dictionary with keys

How to initialize a dictionary with keys

By using iterating through a list we can easily check how to initialize a dictionary with keys.

Example:

new_keys = ["u", "v", "t"]

dict = {}
for x in new_keys:
    dict[x] = None
print(dict)

Here is the Screenshot of the following given code

Python dictionary initialize with keys iterate method
Python dictionary initialize with keys iterate method

How to initialize a dictionary with keys

By using the zip() function to declare a dictionary with keys and the same length value and pass as an argument list-keys.

Example:

Ini_keys = ["z", "a", "l"]
  
my_dict = dict(zip(Ini_keys, [None]*len(Ini_keys)))
print(my_dict)

Here is the Screenshot of the following given code

Python dictionary initialize with keys zip method
Python dictionary initialize with keys zip method

Python initialize dictionary from string

  • Let us see how to initialize a dictionary from string using the eval() method.
  • It is a built-in function mostly used in Python and it evaluates the string expression and returns the output as a dictionary form.

Example:

let’s take an example and check how to initialize a dictionary from a string in Python.

new_str = "{'p':49, 'q':53, 'r':45}"

to_Dict = eval(new_str)
print("Initialize Dictionary from string:",to_Dict)

Here is the Screenshot of the following given code

Python initialize dictionary from string
Python initialize dictionary from string

Python initialize dictionary list comprehension

  • Let us see how to initialize a dictionary with a list comprehension method.
  • list comprehension takes the key value form in iterable sequence.

Example:

new_key = ['z','y','u','w','r']
new_value = [4,5,6,2,9]  

to_dict = { k:v for (k,v) in zip(new_key, new_value)}  
print (to_dict)

Here is the Screenshot of the following given code

Python initialize dictionary list comprehension
Python initialize dictionary list comprehension

This is how to initialize a dictionary with a list comprehension method.

You may like the following Python tutorials:

Here we learned, Python dictionary initialize and the below examples:

  • Python dictionary initialize empty
  • Python dictionary initialize to 0
  • Python dictionary initialize with none value
  • Python dictionary initialize with values
  • Python dictionary initialize with empty list
  • Python dictionary initialize if empty
  • Python initialize dictionary with keys and values
  • Python initialize dictionary with for loop
  • Python initialize dictionary with multiple Keys
  • Python initialize dictionary with keys
  • Python initialize dictionary from string
  • Python initialize dictionary list comprehension