Python dict() Function

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

Syntax

dict(**kwarg)
dict([mapping, **kwarg])
dict([iterable, **kwarg])

Parameters

The keyword argument is preceded by an identifier (e.g., name=). Hence, the keyword argument of a form kwarg=value is passed to a dict() constructor to create dictionaries.

  1. kwarg: It’s the keyword argument and is optional in the function. The **kwarg lets you take an arbitrary number of keyword arguments.
  2. mapping: It is also optional (Another dictionary).
  3. iterable: It is also optional. An iterable is a collection of key-value pairs where keys must be unique and immutable.

Return value

  1. If no argument is passed, it creates an empty dictionary.
  2. If a positional argument is given, a dictionary is created with the same key-value pairs. Otherwise, pass an iterable object.
  3. If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument.

Example 1: How to Use dict() Function

Creating a dictionary from keyword arguments.

main_dict = dict(a=1, b=2, c=3)

print("Dictionary from keyword arguments:", main_dict)

Output

Dictionary from keyword arguments: {'a': 1, 'b': 2, 'c': 3}

Example 2: Creating a dictionary from an iterable

Creating a dictionary from an iterable containing key-value pairs:

main_list = [('a', 1), ('b', 2), ('c', 3)]
main_dict = dict(main_list)

print("Dictionary from iterable of key-value pairs:", main_dict)

Output

Dictionary from iterable of key-value pairs: {'a': 1, 'b': 2, 'c': 3}

Example 3: Create a dictionary using mapping

Creating a dictionary from another dictionary or mapping.

original_dict = {'a': 1, 'b': 2, 'c': 3}
main_dict = dict(original_dict)

print("Dictionary from another dictionary:", main_dict)

Output

Dictionary from another dictionary: {'a': 1, 'b': 2, 'c': 3}

That’s it.

Leave a Comment

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