×

How to create a dictionary in Python?

How to create a dictionary in python

Dictionary is a data structure in Python that represents our data in the form of keys and values.

Each value in a dictionary can be accessed using its corresponding key.

Let us have a look at some more properties of a Dictionary-

  1. All the keys in a dictionary should be unique.
  2. The keys in the dictionary are case-sensitive which means 'shape' and 'SHAPE' are treated as two different keys.

Let us have a look that how we can create a dictionary in Python-

Syntax of Dictionary

a={'Fruit_name':'Apple','Color':'Red','Shape':'Spherical'}

Now let’s see after creating it how we can verify this data structure.

The following program illustrates how we can check the type-

 #using dictionary
 a={'Fruit_name':'Apple','Color':'Red','Shape':'Spherical'}
 print(a)
 print(type(a)) 

INPUT-

OUTPUT-

In the output, we can observe the dictionary ‘a’ is printed that contains three keys and type() returns its datatype.

The next thing that we will discuss in this article is how we can access the values in our dictionary.

Accessing values in a dictionary

In the following program, we have used the keys to access the values of our dictionary.

 #using dictionary
 a={'Fruit_name':'Apple','Color':'Red','Shape':'Spherical'}
 print(a)
 print(type(a))
 #accessing elements using keys
 print(a['Fruit_name'])
 print(a['Color'])
 print(a['Shape']) 

INPUT-

OUTPUT-

In the output, we can observe the following things-

  1. The dictionary ‘a’ is printed.
  2. The data type is returned which is <class ‘dict’>.
  3. Then the three values are displayed when we access them using the keys 'Fruit-Name', 'Color', and 'Shape'.

Now, let us see what are the different ways of creating a dictionary in Python.

WAYS TO CREATE A DICTIONARY

Here, we will try to understand this with the help of four methods-

  1. Simple creation of a list
  2. Using dict()
  3. Using {}
  4. Using defaultdict

In the first method, we can see a dictionary is created using the most basic approach where we have specified our keys and values in the curly braces.

Following program illustrates the same.

 #creating a dictionary
 a={'Fruit_name':'Apple','Color':'Red','Shape':'Spherical'}
 print(a)
 print("The type of a is {}".format(type(a))) 

INPUT-

OUTPUT-

On executing the given program, the expected results are displayed.

The second method that we will discuss here is creating a dictionary using dict().

So, here we have declared object a as dict() and then defined our dictionary.

Following program illustrates the same-

 #creating a dictionary
 a=dict()
 a={'Fruit_name':'Apple','Color':'Red','Shape':'Spherical'}
 print(a)
 print("The type of a is {}".format(type(a))) 

INPUT-

OUTPUT-

On executing the code, the expected results are displayed.

The third method that we will discuss is creating a dictionary by declaring a as {} and then defining the value for each key.

Then we have printed a and its data type.

Following program illustrates the same-

 #creating a dictionary
 a={}
 a["Fruit_Name"]="Apple"
 a["Color"]="Red"
 a["Shape"]="Spherical"
 print(a)
 print("The type of a is {}".format(type(a))) 

INPUT-

OUTPUT-

The last method that we will discuss is creating a dictionary using defaultdict().

Here we have provided a list that contains the key, value pairs and then applied the method defaultdict() to it and then added each value corresponding to the key, and then printed it.

Following program illustrates the same-

 #using defaultdict
 from collections import defaultdict
 lst=[('Fruit_Name','Apple'),('Color','Red'),('Shape','Spherical'),('Fruit_Name','Grapes')]
 dict_fruits=defaultdict(list)
 for key,value in lst:
     dict_fruits[key].append(value)
 print(dict_fruits) 

INPUT-

OUTPUT-

In the output, we can observe that first of all it tells us that it belongs to the <class 'list'> which is followed by a dictionary that has the keys and all the values are in the form of lists.

The next thing we will discuss in this article is how we add and modify the values in our dictionary.

Updating dictionary

Let us first see how we can add an element in the dictionary.

Following program illustrates the same-

 #adding an element in dictionary
 a={'Fruit_Name':'Apple','Color':'Red','Shape':'Spherical'}
 print(a)
 print("The type of a is {}".format(type(a)))
 a['Fruit_Name1']='Grapes'
 print(a) 

INPUT-

OUTPUT-

In the output, we can observe the new key-value pair being added.

Next, we will see how we can modify the value of a particular key.

Following program illustrates the same-

 #modifying an element in dictionary
 a={'Fruit_Name':'Apple','Color':'Red','Shape':'Spherical'}
 print(a)
 print("The type of a is {}".format(type(a)))
 a['Color']='Green'
 print(a) 

INPUT-

OUTPUT-

In the output, we can observe the value of color has been modified from ‘Red’ to ‘Green’.

In the last section of this article, we will take a brief idea of the methods that are used in a dictionary.

Methods used in Dictionary

  1. len() – The len() method returns the length of our dictionary. In the output, we can see that it comes out to be 3.
 #methods on dictionary
 a={'Fruit_Name':'Apple','Color':'Red','Shape':'Spherical'}
 print(len(a)) 
  • Dict.get(‘key’)-In this ‘Dict’ refers to the name of the dictionary and ‘key’ refers to the name of the key whose value we would like to fetch. We can see in the example it returns ‘Red’ when we provide the key ‘Color’.
 #methods on dictionary
 a={'Fruit_Name':'Apple','Color':'Red','Shape':'Spherical'}
 print(a.get('Color')) 
  • Dict.items()-In this method, ‘Dict’ refers to the name of the dictionary and it returns all the key-value pairs present in the dictionary.
 #methods on dictionary
 a={'Fruit_Name':'Apple','Color':'Red','Shape':'Spherical'}
 print(a.items()) 
  • Dict.keys()-In this method, 'Dict' refers to the name of the dictionary and it returns all the keys present in the dictionary. In the output, we can see it returns the keys 'Fruit_Name', 'Color', and 'Shape'.
 #methods on dictionary
 a={'Fruit_Name':'Apple','Color':'Red','Shape':'Spherical'}
 print(a.keys()) 
  • Dict.values()-In this method, ‘Dict’ refers to the name of the dictionary and it returns all the values present in the dictionary. In the output, we can see it returns the values ‘Apple’,’Red’ and ‘Spherical’.
 #methods on dictionary
 a={'Fruit_Name':'Apple','Color':'Red','Shape':'Spherical'}
 print(a.values()) 

So, in this article, we discussed dictionaries, how we can access them, how we can create them, and what are the different methods that we can apply to them.


Related Topics

PyDev with Python IDE

What is IDE? Integrated Development Environment is the abbreviation of IDE. It is a coding tool that automates code editing, finding errors and testing. IDE combines all the developer tools into...

3 minutes read.

Performing Transaction Using Python MySQL

Transaction A Transaction contains a set of SQL commands used to change the data in the dataset. If we say transaction, it means that the data in the database has changed....

3 minutes read.

Division in Python

In this tutorial, we will understand what mathematical operation division is and how is it performed in Python Programming language. We will also focus on the operators being used in...

3 minutes read.

Latest Project Ideas using Python 2024

Python is one of the well-known languages for programming in the contemporary domain of computer science. The demand to adopt Python for IT purposes is steadily increasing because of its...

7 minutes read.

What Does the Percent Sign (%) Mean in Python?

In python, the percent sign is called modulo operator " %, " which returns the rest of partitioning the left-hand operand by the right-hand operand. Example: value1 = 8 value2 = 2 remainder =...

4 minutes read.

Python Simple Interest

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

How to Import Files in Python

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Comment starts with the symbol in Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Python Project Ideas for Beginners

Python project ideas for beginners Advanced Python is an amazing platform to grow and achieve success as a developer in the future. Python is a programming language that can be very...

7 minutes read.

Python Kwargs Example

In this article, we'll talk about Python's kwargs notion. In Python, kwargs has two stars and passes a variable number of keyworded argument lists to the function, whereas args has...

5 minutes read.

Python Logistic Regression with Sklearn & Scikit

In this article, we'll walk through a tutorial for utilising the Python Sklearn (formerly known as Scikit Learn) package to implement logistic regression. To assist you in remembering the concept,...

18 minutes read.

Python Trigonometric Functions

Before jumping right into the functions and how to use them we need to know what do trigonometric functions mean and how many functions does python has. What are Trigonometric functions? Trigonometric...

3 minutes read.

Isodate Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space...

3 minutes read.

Python Abstract Class

An Introduction to Abstract Classes An Abstract Class is one of the most significant concepts of Object-Oriented Programming (OOP). An Abstract class can be deliberated as a blueprint or design for...

6 minutes read.

Python oct() function

Python oct() function The oct() function in Python converts an integer number to an octal string prefixed with “0o”. Syntax oct(x) Parameter x: This parameter represents an Integer Number Return This function returns an octal string. Example 1 #...

1 minute read.

Check if a String is Empty in Python

The string is one of the data types of Python. This data type stores all kinds of data but all the characters must be enclosed using double quotes (""). In...

5 minutes read.

Rank Based Percentile GUI Calculator using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With the capabilities...

3 minutes read.

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical...

3 minutes read.

Python while loop

Loops are essential in Python or any other programming language, as they help to execute a block of code repetitively. Sometimes, situations arise where you would need to use a piece of code...

2 minutes read.