dict() overview
The dict() function is used to construct a new dictionary in Python. It can be used to create an empty dictionary or pass values as argument.
Dictionaries are unordered, indexed and mutable (can be changed).
dict() to create empty dictionary
To create an empty dictionary, use the dict() function without passing arguments.
# create empty dictionary using dict()
myDict = dict()
print(myDict)
The dict() function created an empty dictionary.
{}
We can verify it by using the type() function.
# verify dict type
myDict = dict()
print(type(myDict))
The type of the created object is returned.
dict() using keyword arguments
To create an non-empty dictionary, pass the comma-separated values in the first argument.
# create a dictionary using dict()
myDict = dict(name = "Mike", age = 26)
print(myDict)
The dictionary is created and printed.
{'name': 'Mike', 'age': 26}
dict() using mapping
# using dict() with mapping
myDict = dict({'name': 'Mike', 'age': 26})
print(myDict)
The dictionary is created and printed.
{'name': 'Mike', 'age': 26}
dict() using iterable
# dict() using iterable
myDict = dict([('name', 'Mike'), ('age', 26)])
print(myDict)
The dictionary is created and printed.
{'name': 'Mike', 'age': 26}
dict() using mixed input
It is possible to pass mixed arguments to the dict() function.
#dict() using mixed arguments
myDict = dict({'name': 'Mike', 'language': 'python'}, age=26)
print(myDict)
The dictionary is created and printed.
{'name': 'Mike', 'language': 'python', 'age': 26}
dict() syntax
The syntax of the dict() function is:
dict(**kwarg)
dict(mapping, **kwarg)
dict(iterable, **kwarg)
dict() arguments
The dict() function accepts keyword arguments, mapping objects or iterables.
Arguments passed to the dict() function can be mixed
If no argument is passed, an empty dictionary is created.
dict() return values
The dict() function returns None.
related functions and methods
Some related functions of dict() are functions to create other data structures like list() or tuple().