×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python dict() Function: Use, Syntax, and Examples

By IncludeHelp Last updated : December 07, 2024

Python dict() function

The dict() function is a library function in Python, it is used to create a dictionary with keywords( Ids) and values (s), it accepts a set of values with keywords, values and returns a dictionary.

Consider the below example with sample input/output values:

Input:
# creating dictionary 
std_info = dict(name = "Amit shukla", age = 21, course = "B.Tect (CS)")

# printing the value of dictionary 
print("std_info:", std_info)
    
Output:
std_info: {'course': 'B.Tect (CS)', 'age': 21, 'name': 'Amit shukla'}

Syntax

The following is the syntax of dict() function:

dict(keyword1=value1, keyword2=value2, ...)

Parameter(s):

The following are the parameter(s):

  • keyword1=value1, keyword2=value2, ... – The set of keywords and values to create a dictionary.

Return Value

The return type of dict() function is <class 'dict'>, it returns dictionary.

Python dict() Function: Example 1

Python code to create a dictionary using dict() function.

# python code to demonstrate example of 
# dict() function

# creating dictionary 
std_info = dict(name = "Amit shukla", age = 21, course = "B.Tect (CS)")

# printing type 
print("type of std_info: ", type(std_info))

# printing the value of dictionary 
print("std_info:", std_info)

Output

type of std_info:  <class 'dict'>
std_info: {'course': 'B.Tect (CS)', 'age': 21, 'name': 'Amit shukla'}

Python dict() Function: Example 2

In this example, we are going to create a deep copy of an existing dictionary using the dict() function.

# Create a deep copy of the dictionary
# using dict() function

#  dictionary
std_info = {"name": "Amit shukla", "age": 21, "course": "B.Tect (CS)"}

# Create deep copy
result = dict(std_info)

# Print both dictionary
print("std_info:", std_info)
print("result:", result)

Output

std_info: {'name': 'Amit shukla', 'age': 21, 'course': 'B.Tect (CS)'}
result: {'name': 'Amit shukla', 'age': 21, 'course': 'B.Tect (CS)'}


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.