Skip to main content

Python dict() Function

The dict() built-in function in Python is used to create a new dictionary object from various types of inputs, such as keyword arguments, a mapping, or an iterable.

Syntax

There are different constructors:

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

dict() Parameters

Python dict() function parameters:

ParameterConditionDescription
**kwargsOptionalEach keyword argument represents a key-value pair, where the key is the keyword and the value is the argument.
mappingOptionalAny mapping object or subclass (like another dictionary).
iterableOptionalAn iterable producing iterables of length two, typically tuples or lists, where the first element is the key.
note

**kwarg let you take an arbitrary number of keyword arguments.

dict() Return Value

Python dict() function returns

Examples

Example 1: create Dictionary Using keyword arguments only

numbers = dict(x=1, y=2)
print('numbers =', numbers)
print(type(numbers))

empty = dict()
print('empty =', empty)
print(type(empty))

output

numbers = {'x': 1, 'y': 2}
<class 'dict'>
empty = {}
<class 'dict'>

Example 2: create Dictionary using Iterable

# keyword argument is not passed
numbers1 = dict([('x', 123), ('y', -123)])
print('numbers1 =',numbers1)

# keyword argument is also passed
numbers2 = dict([('x', 123), ('y', -123)], z=8)
print('numbers2 =',numbers2)

# zip() creates an iterable in Python 3
numbers3 = dict(zip(['x', 'y', 'z'], [1, 2, 3]))
print('numbers3 =',numbers3)

output

numbers1 = {'x': 123, 'y': -123}
numbers2 = {'x': 123, 'y': -123, 'z': 8}
numbers3 = {'x': 1, 'y': 2, 'z': 3}

Example 3: create Dictionary using Mapping

numbers1 = dict({'x': 1, 'y': 2})
print('numbers1 =',numbers1)

# you don't need to use dict() in above code
numbers2 = {'x': 1, 'y': 2}
print('numbers2 =',numbers2)

# keyword argument is also passed
numbers3 = dict({'x': 1, 'y': 2}, z=8)
print('numbers3 =',numbers3)

output

numbers1 = {'x': 1, 'y': 2}
numbers2 = {'x': 1, 'y': 2}
numbers3 = {'x': 1, 'y': 2, 'z': 8}