The dict () function in Python
In Python, the dict () function creates a dictionary type value. Quantrimang will learn more about the syntax, parameters and usage of the dict () function through this article. Invites you to read the track.
The dict () function in Python Picture 1
The syntax of the dict () function in Python
The dict () function has several different forms as follows:
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
Note: ** kwarg allows you to pass as many parameters as you want without knowing the number in advance.
The parameter using the keyword argument is a pre-defined parameter. So the keyword argument is in the form kwarg = the value will be passed to the dict () function to create the dictionary.
Dict () does not return any value.
Example 1: Create Dictionary using the keyword argument.
numbers = dict(x=5, y=0)
print('numbers = ',numbers)
print(type(numbers))
empty = dict()
print('empty = ',empty)
print(type(empty))
Run the program, the result is:
empty = dict()
print('empty = ',empty)
print(type(empty))
Example 2: Create Dictionary uses Iterable
# keyword argument không được truyền vào
numbers1 = dict([('x', 5), ('y', -5)])
print('numbers1 =',numbers1)
# keyword argument được truyền vào
numbers2 = dict([('x', 5), ('y', -5)], z=8)
print('numbers2 =',numbers2)
# zip() tạo iterable trong Python 3
numbers3 = dict(dict(zip(['x', 'y', 'z'], [1, 2, 3])))
print('numbers3 =',numbers3)
Run the program, the result is:
numbers1 = {'y': -5, 'x': 5}
numbers2 = {'z': 8, 'y': -5, 'x': 5}
numbers3 = {'z': 3, 'y': 2, 'x': 1}
Example 3: Create Dictionary uses mapping
numbers1 = dict({'x': 4, 'y': 5})
print('numbers1 =',numbers1)
# Không nhất thiết phải dùng dict()
numbers2 = {'x': 4, 'y': 5}
print('numbers2 =',numbers2)
# keyword argument được truyền vào
numbers3 = dict({'x': 4, 'y': 5}, z=8)
print('numbers3 =',numbers3)
The result is:
numbers1 = {'x': 4, 'y': 5}
numbers2 = {'x': 4, 'y': 5}
numbers3 = {'x': 4, 'z': 8, 'y': 5}
Previous article: Function delattr () in Python
Next article: Function in dir () Python
You should read it
- Int () function in Python
- The function dir () in Python
- The ord () function in Python
- The function id () in Python
- Max () function in Python
- Zip () function in Python
- The compile () function in Python
- The iter () function in Python
- Exec () function in Python
- Hex () function in Python
- The function set () in Python
- The globals () function in Python