Python dict() Function
Description
dict() The function is used to create a dictionary.
Syntax
dict Syntax:
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
Parameter Description:
- **kwargs -- keyword arguments.
- mapping -- a container of elements; a mapping type is an associative container type that stores the mapping relationship between objects.
- iterable -- an iterable object.
Return Value
Returns a dictionary.
Example
The following examples show the use of dict:
dict
(
)
Create an empty dictionary
{} >>>
dict
(
a
=
'
a
'
,
b
=
'
b
'
,
t
=
'
t
'
)
Pass keyword arguments
{
'
a
'
:
'
a
'
,
'
b
'
:
'
b
'
,
'
t
'
:
'
t
'
} >>>
dict
(
zip
(
[
'
one
'
,
'
two
'
,
'
three
'
]
,
[
1
,
2
,
3
]
)
)
Construct a dictionary using the mapping function
{
'
three
'
:
3
,
'
two
'
:
2
,
'
one
'
:
1
} >>>
dict
(
[
(
'
one
'
,
1
)
,
(
'
two
'
,
2
)
,
(
'
three
'
,
3
)
]
)
Construct a dictionary using an iterable object
{
'
three
'
:
3
,
'
two
'
:
2
,
'
one
'
:
1
} >>>
Create a dictionary using only keyword arguments
Example
numbers
=
dict
(
x
=
5
,
y
=
0
)
(
'numbers ='
,
numbers
)
(
type
(
numbers
)
)
empty
=
dict
(
)
(
'empty ='
,
empty
)
(
type
(
empty
)
)
The output of the above example is:
numbers = {'y': 0, 'x': 5}
empty = {}
Create a dictionary using an iterable object
Example
No keyword arguments set
numbers1
=
dict
(
[
(
'x'
,
5
)
,
(
'y'
,
5
)
]
)
(
'numbers1 ='
,
numbers1
)
Set keyword arguments
numbers2
=
dict
(
[
(
'x'
,
5
)
,
(
'y'
,
5
)
]
,
z
=
8
)
(
'numbers2 ='
,
numbers2
)
zip() creates an iterable object
numbers3
=
dict
(
dict
(
zip
(
[
'x'
,
'y'
,
'z'
]
,
[
1
,
2
,
3
]
)
)
)
(
'numbers3 ='
,
numbers3
)
The output of the above example is:
numbers1 = {'y': -5, 'x': 5}
numbers2 = {'z': 8, 'y': -5, 'x': 5}
numbers3 = {'z': 3, 'y': 2, 'x': 1}
Create a dictionary using a mapping
A mapping type is an associative container type that stores the mapping relationship between objects.
Example
numbers1
=
dict
(
{
'x'
:
4
,
'y'
:
5
}
)
(
'numbers1 ='
,
numbers1
)
The following code does not need to use dict()
numbers2
=
{
'x'
:
4
,
'y'
:
5
}
(
'numbers2 ='
,
numbers2
)
Keyword arguments will be passed
numbers3
=
dict
(
{
'x'
:
4
,
'y'
:
5
}
,
z
=
8
)
(
'numbers3 ='
,
numbers3
)
The output of the above example is:
numbers1 = {'x': 4, 'y': 5}
numbers2 = {'x': 4, 'y': 5}
numbers3 = {'x': 4, 'z': 8, 'y': 5}
Python built-in function