dict(): Create Dictionary Object Function
dict | |
---|---|
Language | Python |
Category | Function |
Part Of | Built In Functions |
Named Arguments Count | 0 |
Unnamed Arguments Count | 1/2 |
Official Documentation | dict Function |
1 Description
The Python dict
function is used to create a dictionary object.
2 Prototypes
2.1 Keyword Arguments Prototype
Below is the keyword arguments prototype for the dict
function. See example 6.1.
dict(**keyword_arguments)
2.2 Mapping Prototype
Below is the mapping prototype for the dict
function. See example 6.2.
dict(mapping, **keyword_arguments)
2.3 Iterable Prototype
Below is the iterable prototype for the dict
function. See example 6.3.
dict(iterable, **keyword_arguments)
3 Arguments
dict Function Arguments | ||||
---|---|---|---|---|
Name | Type | Default Value | Category | Description |
keyword_arguments |
Unnamed argument(s) | A comma separated list of key=value pairs. | ||
mapping |
mapping |
Unnamed argument(s) | Used to initialize a dictionary object with the values contained in a mapping object. |
|
iterable |
iterable |
Unnamed argument(s) | Used to initialize a dictionary object with the values contained in an iterable object. |
4 Returns
dict Function Returns | |
---|---|
Return Type | Explanation |
dict |
The dict function will always a dictionary type object. |
5 Raises
dict Function Raises | |
---|---|
Exception Type | Raised When |
ValueError |
When a sequence that is not length 2 is passed to the dict function. |
6 Examples
6.1 Create Dictionary From Key Value Pairs
#!/usr/bin/python3
def main():
animal_1 = dict(category="horse", name="George", weight="800lbs")
animal_2 = dict(category="chicken", name="Alex", weight="4lbs")
print(animal_1)
print(animal_2)
if __name__ == "__main__":
main()
user-1@vm:~/Documents$ ./dict_example_1.py
{'category': 'horse', 'name': 'George', 'weight': '800lbs'}
{'category': 'chicken', 'name': 'Alex', 'weight': '4lbs'}
user-1@vm:~/Documents$
6.2 Create Dictionary From Existing Dictionary
#!/usr/bin/python3
def main():
animal_1 = dict(category="horse", name="George", weight="800lbs")
animal_2 = dict(animal_1)
print(animal_1)
print(animal_2)
if __name__ == "__main__":
main()
user-1@vm:~/Documents$ ./dict_example_2.py
{'category': 'horse', 'name': 'George', 'weight': '800lbs'}
{'category': 'horse', 'name': 'George', 'weight': '800lbs'}
user-1@vm:~/Documents$
6.3 Create Dictionary From Iterator
#!/usr/bin/python3
def main():
my_iterable = iter(
(
("first_name", "George"),
("last_name", "Windsor"),
("height", "6'0")
)
)
my_dict = dict(my_iterable)
print(my_dict)
if __name__ == "__main__":
main()
user-1@vm:~/Documents$ ./dict_example_2.py
{'first_name': 'George', 'last_name': 'Windsor', 'height': "6'0"}
user-1@vm:~/Documents$
This document was last updated: