How to create a dictionary in Python?

PythonServer Side ProgrammingProgramming

A Dictionary in Python is a type of data structure.It consists of a collection of key-value pairs. Each key in the dictionary is unique. Each unique key in the dictionary is associated to its value. Thus, Dictionary holds key : value pairs.

We will be discussing how to create a dictionary in Python.

Create a Dictionary

A dictionary in Python can be created by placing various key: value pairs inside curly braces .The key:value pairs are separated from each other using commas(,). The values in the dictionary can be of any datatype and can be duplicated. However, the keys in the dictionary cannot be repeated and must be immutable.

Dictionary keys are case-sensitive.This means two keys with same names but different cases will be treated distinctly.

Example

 Live Demo

dict1={1:"Tutorials",2:"Point",3:1116}
print("Dictionary 1",dict1)
dict2={1:"TutorialsPoint","TP":"DictionaryTutorial"}
print("Dictionary 2",dict2)

Output

Dictionary 1 {1: 'Tutorials', 2: 'Point', 3: 1116}
Dictionary 2 {1: 'TutorialsPoint', 'TP': 'DictionaryTutorial'}

As clear from the above example, the keys and values can have any datatype in a dictionary. But all the keys must be unique.

What if two keys in dictionary are given same name?

Let’s observe with the help of an example.

Example

 Live Demo

dict1={1:"Tutorials",1:"Point",3:1116}
print("Dictionary 1",dict1)

Output

Dictionary 1 {1: 'Point', 3: 1116}

The above example shows that if two keys in a dictionary are given same name, the previous key value is just overwritten.Here the “Tutorials” in key “1” is overwritten with “Point”.

We can have both these values or even more in a single key by assigning lists to keys.

Using “dict()” method

We can create dictionary in Python using the dict() method. Inside the dict() method, we will define the key : value pairs of the dictionary.

Example

 Live Demo

dict1=dict({1:"Tutorials",1:"Point",3:1116})
print("Dictionary 1",dict1)
dict2=dict([(1,"Tutorials"),(2,"Point")])
print("Dictionary 2",dict2)

The dict2 is a dictionary created using dict() method with each item as a Pair.

Output

Dictionary 1 {1: 'Point', 3: 1116}
Dictionary 2 {1: 'Tutorials', 2: 'Point'}

Creating Empty Dictionary

An empty dictionary can be created by simply placing two curly braces {}.

Example

 Live Demo

dict1={}
print("Dictionary 1",dict1)

Output

Dictionary 1 {}

Creating Nested Dictionary

Nested Dictionary as the name suggests means a dictionary inside a dictionary. In nested dictionary, a key can contain another dictionary.

Example

 Live Demo

dict1={1:"Tutorials",2:"Point",3:{'A':"Welcome",'B':"To",'C':"TutorialsPoint"}}
print(dict1)

Output

{1: 'Tutorials', 2: 'Point', 3: {'A': 'Welcome', 'B': 'To', 'C': 'TutorialsPoint'}}

In the above example, the key ‘3’ contains another dictionary.Thus, dict1 is a nested dictionary.

raja
Published on 10-Mar-2021 14:04:39
Advertisements