Python dict() Function
dict() is a built-in Python function that creates dictionaries.
A dictionary is a key-value data structure in Python, where each key maps to a value.dict() The function can create dictionaries in several ways.
Word meaning: dict Is dictionaryis short for (dictionary).
Basic syntax and parameters
Syntax format
dict()
dict(mapping)
dict(**kwargs)
dict(iterable, **kwargs)
Parameter Description
- Parameter mapping:
- Type: mapping object (such as a dictionary)
- Description: create a new dictionary from a mapping object.
- Parameter kwargs:
- Type: keyword arguments
- Description: create a dictionary using keyword arguments.
- Parameter iterable:
- Type: iterable
- Description: an iterable whose elements are key/value pairs.
Function description
- Return Value: returns a dictionary object.
- Feature: dictionary keys must be of an immutable type (such as strings, numbers, tuples).
Example
Example 1: creating dictionaries
Example
Empty dictionary
d
=
dict
(
)
(
d
)
Output: {}
Keyword arguments (most common)
d
=
dict
(
name
=
"Tom"
,
age
=
20
)
(
d
)
Output: {'name': 'Tom', 'age': 20}
Create from a mapping object
d1
=
{
"name"
:
"Tom"
}
d2
=
dict
(
d1
)
(
d2
)
Output: {'name': 'Tom'}
Create from an iterable (whose elements are key/value pairs)
pairs
=
[
(
"name"
,
"Tom"
)
,
(
"age"
,
20
)
]
d
=
dict
(
pairs
)
(
d
)
Output: {'name': 'Tom', 'age': 20}
Create from zip
keys
=
[
"name"
,
"age"
,
"city"
]
values
=
[
"Tom"
,
20
,
"Beijing"
]
d
=
dict
(
zip
(
keys
,
values
)
)
(
d
)
Output: {'name': 'Tom', 'age': 20, 'city': 'Beijing'}
Expected output:
{}
{'name': 'Tom', 'age': 20}
{'name': 'Tom'}
{'name': 'Tom', 'age': 20}
{'name': 'Tom', 'age': 20, 'city': 'Beijing'}
Code analysis:
- Keyword arguments are the most common way to create a dictionary.
- Elements of the iterable must be key/value pairs (tuple or list).
dict(zip())is a common trick for merging two lists into a dictionary.
Example 2: dictionary operations
Example
Access values
d
=
{
"name"
:
"Tom"
,
"age"
:
20
}
(
d
[
"name"
]
)
Output: Tom
(
d.
get
(
"age"
)
)
Output: 20
Add / modify
d
[
"city"
]
=
"Beijing"
d
[
"age"
]
=
21
(
d
)
Output: {'name': 'Tom', 'age': 21, 'city': 'Beijing'}
Delete
del
d
[
"age"
]
(
d
)
Output: {'name': 'Tom', 'city': 'Beijing'}
Iteration
for
key
,
value
in
d.
items
(
)
:
(
f
"{key}: {value}"
)
Expected output:
Tom
20
{'name': 'Tom', 'age': 21, 'city': 'Beijing'}
{'name': 'Tom', 'city': 'Beijing'}
name: Tom
city: Beijing
Dictionaries support rich operations: access, add, modify, delete, iterate, and so on.
Python3 built-in function