How To Create An Empty Dictionary In Python


Estimated reading time: 2 minutes

In our recent video Python dictionary interview questions, we discussed a number of topics around Python dictionaries .

Here we will discuss how to create an empty dictionary.

In the below code, you will see there are two ways to create:

  1. Use a variable that is equal to empty curly brackets
  2. Just make an empty variable equal to the dict() function.
  3. Use the key/values in a list.
  4. Use a function
  5. Use List comprehension

Creating empty dictionaries has many benefits as you can manipulate them as they are mutable.

Also, they can grow and shrink as you need, you just need to make sure that any new key you add is unique and not already stored in the dictionary.

Another thing to note about them is that they are unordered.

Finally, if you are adding data to a dictionary, the keys are case-sensitive, so the same key can exist in the dictionary, but it has to be different regards the case applied to it.

## How do you create an empty dictionary?
# empty_dict1 = {}
# empty_dict2 = dict()
# print(empty_dict1)
# print(empty_dict2)
# print(type(empty_dict1))
# print(type(empty_dict2))

#Use Keys,values in lists
# list_keys = []
# List_values = []
#
# n = dict(zip(list_keys, List_values))
# print(n)
# print(type(n))

# Note using Zip just allows you to iterate over two lists in parallel  , and the output is a set of pairs


##Use a function ##
#
# def create_dictionary():
#     d = {}
#     print(d)
#     print(type(d))
#
# create_dictionary()


##Use list comprehension##
# loop_list = []
# d = { i: j for i, j in enumerate(loop_list)}
# print(d)
# print(type(d))

 

Leave a Reply

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