22.4 C
New York
Thursday, March 28, 2024
HomeProgrammingPythonHow To Create An Empty Dictionary in Python

How To Create An Empty Dictionary in Python

In this tutorial, we will explore how to create an empty dictionary in Python using various methods. You will also learn about various dictionary methods.

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 using curly brackets ({}) with the assignment operator.

You can use the type() function to display the data type. In the example below, we will create and display an empty dictionary 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'>

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'>

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}

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 whether the dictionary is empty using 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. 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()

The 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

This method will use the bool() Python function to check whether a dictionary is empty. 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

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

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'}

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

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'}

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 whether a key exists in a dictionary.

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])

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'])

6. items()

This Python dictionary method returns a view object that 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')])

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 learned about different methods to check whether a dictionary is empty. And finally, we explored different Python dictionary methods such as copy(), get(), update(), and many others.

Himanshu Tyagi
Himanshu Tyagi
Hello Friends! I am Himanshu, a hobbyist programmer, tech enthusiast, and digital content creator. With CodeItBro, my mission is to promote coding and help people from non-tech backgrounds to learn this modern-age skill!
RELATED ARTICLES