How To Create An Empty Dictionary in Python

11

Dictionary in Python stores data as key-value pairs. In this article, we will discuss how to create an empty dictionary in Python and various Dictionary methods such as copy(), get(), update(), etc.

A dictionary in Python is a changeable collection, ordered, and does not allow duplicates. Keys will be unique, and their values can be the same. Do note that in Python 3.7 and above, dictionaries are ordered.

In previous versions, such as Python 3.6 or older, dictionaries used to be unordered. You can create dictionaries using curly brackets {}, as shown below.

Syntax:

{key:value,........................,key:value}

Where key and value can be string or integer.

How To Create An Empty Dictionary in Python

empty dictionary in python

Also ReadHow to Exit Python Program [4 Methods]

Method 1: Using {}

We can create an empty dictionary simply by using curly brackets ({}) with the assignment operator.

To display the data type, you can use the type() function. In the example below, we will create an empty dictionary and display it using the print() function.

Example:

#create an empty dictionary
my_dictionary={}

#display
print(my_dictionary)

#get the type
print(type(my_dictionary))

Output:

{}
<class 'dict'>

Also ReadHow to Convert Python Tuples to Lists

Method 2: Dict() method

Dict() is a Python method that you can use to create a dictionary. You can pass items from the dictionary as arguments in this method.

We will use the dict() method to create an empty dictionary in this method.

dict()

Example:

#create an empty dictionary using dict
my_dictionary=dict()

#display
print(my_dictionary)

#get the type
print(type(my_dictionary))

Output:

{}
<class 'dict'>

Also ReadHow to Handle String Index Out of Range Error In Python

Create an empty dictionary with keys

Here we will see how to create an empty dictionary with only keys and no values. We can use none to create empty values for each key in the dictionary.

Here’s the syntax for the same.

Syntax:

{'key':None,......}

Example:

In this example, we will create a dictionary with 5 integer keys with None values and display the dictionary.

#create an empty dictionary with 5 keys 
my_dictionary={12: None, 34: None, 45: None,54:None,100:None}

#display
print(my_dictionary)

Output:

{12: None, 34: None, 45: None, 54: None, 100: None}

Also ReadPython For Loop Index With Examples

Create an empty nested dictionary

The data structure in which a dictionary contains multiple dictionaries is a nested dictionary. Now, we will see how to create an empty nested dictionary.

Syntax:

{key:{key:value},...............}

We can create this by specifying empty keys and values.

Example:

#create an empty nested dictionary
my_dictionary={ '': { }, '': { },'': { }, '': { },'': { }, '': { }}

#display
print(my_dictionary)

Output:

{'': {}}

Also ReadHow to Reverse an Array In Python [Flip Array]

How to Check if a Dictionary is Empty or Not

We can check if the dictionary is empty or not by using any of these methods.

Method 1: Using the if-else condition

This method will use if-else statements in Python to check if a dictionary is empty. First, we will define a dictionary variable and then use if-else statements to check if that dictionary is empty or not.

Let’s understand this with an example.

Example: In this example, we are creating two dictionaries – the first dictionary is empty, and the second dictionary will hold one key-value pair. Next, we will use the if-else statements to display relevant messages.

#create an empty  dictionary
my_dictionary1={}

#check if dictionary is empty
if(my_dictionary1):
  print("Not empty")
else:
  print("empty")

#create an  dictionary with a key and value
my_dictionary2={'key':'codeitbro'}

#check if dictionary is empty
if(my_dictionary2):
  print("Not empty")
else:
  print("empty")

Output:

empty
Not empty

Method 2: Using not operator

You can also use the Python not operator to check whether a dictionary is empty or not. If the dictionary is empty, it will return True; otherwise, False.

Example:

#create an empty  dictionary
my_dictionary1={}

#check if dictionary is empty or not
print(not my_dictionary1 )

#create an  dictionary with a key and value
my_dictionary2={'key':'codeitbro'}

#check if dictionary is empty or not
print(not my_dictionary2 )

Output:

True
False

Also ReadHow to Convert Binary to Decimal in Python [5 Methods]

Method 3: Using bool()

Bool() function returns the boolean value of a specified object. It will return false if:

  • The object is 0
  • The object is empty
  • The object is none
  • The object is false

In this method, we will use the bool() Python function to check if a dictionary is empty or not. If the dictionary is empty, it will return False; otherwise, True.

Example:

In this example, we are creating two dictionaries – the first dictionary is empty, and the second dictionary will hold one key-value pair.

After that, we will use the bool() function to check each of these dictionaries to check if it is empty.

#create an empty  dictionary
my_dictionary1={}

#check if dictionary is empty or not
print(bool( my_dictionary1) )

#create an  dictionary with a key and value
my_dictionary2={'key':'codeitbro'}

#check if dictionary is empty or not
print(bool( my_dictionary2) )

Output:

False
True

Also ReadPython Program To Display Fibonacci Series Up To N Terms

Method 4: Using len() with conditions

Len() will return the dictionary length (number of key-value pairs in a dictionary). If the length equals 0, we can say that a dictionary is empty.

Example:

#create an empty  dictionary
my_dictionary1={}

#check if dictionary is empty or not
if(len(my_dictionary1)==0):
  print("empty")
else:
  print("not empty")

#create an  dictionary with a key and value
my_dictionary2={'key':'codeitbro'}

#check if dictionary is empty or not
if(len(my_dictionary2)==0):
  print("empty")
else:
  print("not empty")

Output:

empty
not empty

Also ReadPython Program To Display Multiplication Table of Any Number

Removing items from a dictionary

We can remove items from a dictionary using clear() and pop() methods.

1. clear()

clear() will delete all the items from the dictionary. It doesn’t take any parameters.

Syntax:

my_dictionary.clear()

where my_dictionary is the input dictionary.

Example: In this example, we will create a dictionary with 5 key-value pairs and clear all the key-value pairs from the dictionary.

#create an dictionary
my_dictionary1={1:"php",2:"java",3:"html/css",4:"IOT",5:"Big-data"}

#display the dictionary
print(my_dictionary1)

#clear the items from the dictionary
my_dictionary1.clear()

#display the dictionary
print(my_dictionary1)

Output:

{1: 'php', 2: 'java', 3: 'html/css', 4: 'IOT', 5: 'Big-data'}
{}

Also ReadHow To Automate Google Search With Python

2. pop()

We can delete a particular item from a dictionary by specifying the key.

Syntax:

my_dictinary.pop("key")

where the key is the key label to be deleted.

Example:

In this example, we will remove the key-3

#create an dictionary
my_dictionary1={1:"php",2:"java",3:"html/css",4:"IOT",5:"Big-data"}

#display the dictionary
print(my_dictionary1)

#clear the item with key 3
my_dictionary1.pop(3)

#display the dictionary
print(my_dictionary1)

Output:

{1: 'php', 2: 'java', 3: 'html/css', 4: 'IOT', 5: 'Big-data'}
{1: 'php', 2: 'java', 4: 'IOT', 5: 'Big-data'}

Also ReadPython Program To Check If a Number is Odd or Even

Python Dictionary Methods

Let’s explore some basic dictionary methods.

Dictionary Function Purpose
copy()  Copy items of one dictionary to another. It doesn’t modify the original dictionary.
get()   It returns the value of an item with a specified key.
update()  Update dictionary items with items from another dictionary.
keys()  Get all the keys from a dictionary as a list.
values()  Get all the values from a dictionary as a list.
items()  Get all the key-value pairs of a dictionary as a tuple.

1. copy()

copy() is used to copy the items from one dictionary to another. The method returns a shallow copy of a dictionary item. It doesn’t take any arguments.

Syntax:

my_dictionary.copy()

Example: In this example, we will copy the first dictionary to the second dictionary.

#create an dictionary
my_dictionary1={1:"php",2:"java",3:"html/css",4:"IOT",5:"Big-data"}

#display the dictionary
print(my_dictionary1)

#copy the dictionary
my_dictionary2=my_dictionary1.copy()

#display the dictionary
print(my_dictionary2)

Output:

{1: 'php', 2: 'java', 3: 'html/css', 4: 'IOT', 5: 'Big-data'}
{1: 'php', 2: 'java', 3: 'html/css', 4: 'IOT', 5: 'Big-data'}

Also ReadPython App Development Scope—Everything You Should Know

2. get()

You can use the get() dictionary method to fetch an item with a specified key from a dictionary. It takes two parameters:

  • Key: Required parameter. Here you have to pass the key whose value you want to fetch.
  • Value: Optional parameter. A default value to return if the key doesn’t exist in the dictionary.

Syntax:

my_dictionary.get('key')

Example: In this example, we will get the values from the keys.

#create an dictionary
my_dictionary1={1:"php",2:"java",3:"html/css",4:"IOT",5:"Big-data"}

#get the value from key-2
print(my_dictionary1.get(2))

#get the value from key-4
print(my_dictionary1.get(4))

#get the value from key-1
print(my_dictionary1.get(1))

Output:

java
IOT
php

Also Read10 Best Udemy Python Courses for Beginners

3. update()

With the update() function, you can update the value in a dictionary based on a specific key. You can also use it to update a dictionary with items from another dictionary.

Syntax:

my_dictionary.update({'key':'new_value'})

Example: We will update the values based on the keys in this example.

#create an dictionary
my_dictionary1={1:"php",2:"java",3:"html/css",4:"IOT",5:"Big-data"}


#update key 1 with "R lang"
my_dictionary1.update({1:"R lang"})


#update key 5 with "Spark"
my_dictionary1.update({5:"Spark"})

#display
print(my_dictionary1)

Output:

{1: 'R lang', 2: 'java', 3: 'html/css', 4: 'IOT', 5: 'Spark'}

We can also update multiple items using update().

Example: We will update multiple values based on the keys in this example.

#create an dictionary
my_dictionary1={1:"php",2:"java",3:"html/css",4:"IOT",5:"Big-data"}


#update key 1 with "R lang" and key 5 with "Spark"
my_dictionary1.update({1:"R lang",5:"Spark"})


#display
print(my_dictionary1)

Output:

{1: 'R lang', 2: 'java', 3: 'html/css', 4: 'IOT', 5: 'Spark'}

Also Read7 Best Python IDE for Windows [Code Editors]

4. keys()

This method is used to get all the keys from a dictionary. It returns a view object and contains all the keys in a dictionary as a list. Check this Python tutorial to check if a key exists in a dictionary or not.

Syntax:

my_dictionary.keys()

Example:

In this example, we will get the keys from the dictionary.

#create an dictionary
my_dictionary1={1:"php",2:"java",3:"html/css",4:"IOT",5:"Big-data"}


#display the keys
print(my_dictionary1.keys())

Output:

dict_keys([1, 2, 3, 4, 5])

Also Read11 Best Python Libraries for Machine Learning

5. values()

The values() Python method works similarly to keys(). It returns a view object which consists of the values from a dictionary as a list.

Syntax:

my_dictionary.values()

Example:

In this example, we will get the values from the dictionary.

#create an dictionary
my_dictionary1={1:"php",2:"java",3:"html/css",4:"IOT",5:"Big-data"}


#display the values
print(my_dictionary1.values())

Output:

dict_values(['php', 'java', 'html/css', 'IOT', 'Big-data'])

Also Read15 Best Python Libraries for Data Science and Analysis

6. items()

This Python dictionary method returns a view object which includes key-value pairs of a dictionary as a tuple.

Syntax:

my_dictionary.items()

Example:

In this example, we will get the items from the dictionary.

#create an  dictionary
my_dictionary1={1:"php",2:"java",3:"html/css",4:"IOT",5:"Big-data"}


#display the items
print(my_dictionary1.items())

Output:

dict_items([(1, 'php'), (2, 'java'), (3, 'html/css'), (4, 'IOT'), (5, 'Big-data')])

Also Read10 Best Python Libraries for Image Processing

Wrapping Up

In this tutorial, you learned how to create an empty dictionary in Python using various methods. Apart from that, we also covered how to create nested empty dictionaries and empty dictionaries with keys. You also got to know about different methods that you can use to check if a dictionary is empty or not. And finally, we explored different Python dictionary methods such as copy(), get(), update(), and many others.

Next Read: