Python dict() Function

The Python dict() function is used to create a dictionary, which is a collection of key-value pairs.

Creating dictionary using keyword arguments

Syntax

dict(**kwarg)

Parameters

**kwarg(optional): It allows you to take an arbitrary number of keyword arguments, where each keyword argument is treated as a key-value pair in the dictionary.

Return value

  1. If no parameters are provided, it returns an empty dictionary.
  2. If iterable pairs, keyword arguments, or another mapping object is provided, it returns a dictionary containing the key-value pairs derived from these inputs.

Example 1: Creates am empty dictionary

Creates am empty dictionary using dict()

empty_dict = dict()

print(empty_dict)
print(type(empty_dict))

Output

{}
<class 'dict'>

Example 2: Using Keyword Arguments

sample_dict = dict(A=5, B=6, C=7)

print(sample_dict)
print(type(sample_dict))

Output

{'A': 5, 'B': 6, 'C': 7}
<class 'dict'>

Example 3: Dictionary from an iterable

sample_dict = dict([('A', 5), ('B', 6), ('C', 7)], D=8)

print(sample_dict) 
print(type(sample_dict))

Output

{'A': 5, 'B': 6, 'C': 7, 'D': 8}
<class 'dict'>

Example 4: Dictionary from another dictionary

Dictionary from another dictionary

sample_dict = {'A': 5, 'B': 6, 'C': 7}
new_dict = dict(sample_dict)

print(new_dict)

Output

{'A': 5, 'B': 6, 'C': 7}

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.