Python dict() Function with Examples

The dict() built-in python function is a constructor which is used to create a new dictionary in python. A dictionary is an unordered collection....

In this tutorial, we will discuss about the dict() function in python programming language with the help of examples.

Python dict() function

Python dict() function

The built-in python function is a constructor which is used to create a new dictionary in python. A dictionary is an unordered collection of elements and these elements are stored in format or simply we can say that all the elements of the dictionary has the pairs.

Syntax

There are three different forms of dict() constructor;

class dict(**kwarg)

class dict(mapping, **kwarg)

class dict(iterable, **kwarg)

Parameters of dict() function in python 

The dict() function in python takes following three arguments or parameters;

Return value of Python dict() function 

The python function doesn't return any value. It is used to create a python dictionary.

Example 1: How to create Dictionary Using keyword arguments

# A Python program to illustrate dict() function

empty = dict()

print('empty =', empty)

print(type(empty))

num = dict(a=14, b=0, c=2)

print('number =', num)

print(type(num))

Output

empty = {}

<class 'dict'>

number = {'a': 14, 'b': 0, 'c': 2}

<class 'dict'>

Example 2: How to create Dictionary Using Iterable

# A Python program to illustrate dictionary Using Iterable

num1 = dict([('a', 7), ('b', -14)])

print('num1 =',num1)

num2 = dict([('a', 7), ('b', -14)], c=9)

print('num2 =',num2)

# Using zip() 

num3 = dict(dict(zip(['a', 'b', 'c'], [11, 12, 13])))

print('num3 =',num3)

Output

num1 = {'a': 7, 'b': -14}

num2 = {'a': 7, 'b': -14, 'c': 9}

num3 = {'a': 11, 'b': 12, 'c': 13}

Example 3: How to create Dictionary Using Mapping

# A Python program to illustrate Dictionary Using Mapping

num1 = dict({'a': 14, 'b': 9})

print('num =',num1)

# Here you don't need to use dict() function in above code

num2 = {'a': 14, 'b': 9}

print('num2 =',num2)

# Argument is passed

num3 = dict({'a': 14, 'b': 9}, c=2)

print('num3 =',num3)

Output

num = {'a': 14, 'b': 9}

num2 = {'a': 14, 'b': 9}

num3 = {'a': 14, 'b': 9, 'c': 2}