English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The dict() constructor creates a dictionary in Python.
There are several forms of the dict() constructor, respectively:
class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg)
Note:**kwarg allows you to accept any number of keyword arguments.
Keyword arguments are parameters that start with an identifier (such as name=). Therefore, the form of keyword arguments kwarg=value passes kwarg=value to the dict() constructor to create a dictionary.
dict() does not return any value (returns None).
numbers = dict(x=5, y=0) print('numbers =', numbers) print(type(numbers)) empty = dict() print('empty =', empty) print(type(empty))
When running the program, the output is:
numbers = {'y': 0, 'x': 5} <class 'dict'> empty = {} <class 'dict'>
# Do not pass keyword arguments numbers1 = dict([('x', 5), ('y', -5)) print('numbers1 =' ,numbers1) # Keyword arguments are also passed numbers2 = dict([('x', 5), ('y', -5], z=8) print('numbers2 =' ,numbers2) # zip() in Python 3Create an iterable object in numbers3 = dict(dict(zip(['x', 'y', 'z'], [1, 2, 3]) print('numbers3 =' ,numbers3)
When running the program, the output is:
numbers1 = {'y': -5, 'x': 5} numbers2 = {'z': 8, 'y': -5, 'x': 5} numbers3 = {'z': 3, 'y': 2, 'x': 1}
numbers1 = {'x': 4, 'y': 5) print('numbers1 =' ,numbers1) # You do not need to use dict() in the above code numbers2 = {'x': 4, 'y': 5} print('numbers2 =' ,numbers2) # Keyword arguments are also passed numbers3 = {'x': 4, 'y': 5}, z=8) print('numbers3 =' ,numbers3)
When running the program, the output is:
numbers1 = {'x': 4, 'y': 5} numbers2 = {'x': 4, 'y': 5} numbers3 = {'x': 4, 'z': 8, 'y': 5}
Recommended reading: Python dictionary and how to use them Python built-in functions