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:
| Parameter | Condition | Description |
|---|---|---|
**kwargs |
Optional | Each keyword argument represents a key-value pair, where the key is the keyword and the value is the argument. |
mapping |
Optional | Any mapping object or subclass (like another dictionary). |
iterable |
Optional | An iterable producing iterables of length two, typically tuples or lists, where the first element is the key. |
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
numbers1 = dict([('x', 123), ('y', -123)])
print('numbers1 =',numbers1)
numbers2 = dict([('x', 123), ('y', -123)], z=8)
print('numbers2 =',numbers2)
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)
numbers2 = {'x': 1, 'y': 2}
print('numbers2 =',numbers2)
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}