# Create a dictionary with dict based on a list of pairs.# ... List contains tuples with keys and values.
values = [("cat", 1), ("bird", 200)]
lookup = dict(values)
print(lookup.get("bird"))[('cat', 1), ('bird', 200)]
Named arguments. Python supports named arguments. In this syntax, arguments are passed with an equals sign statement. A dictionary can be constructed with this syntax.
# Create a dictionary with named arguments.
animals = dict(bird=1, dog=2, fish=9)
Dict TypeError. The dict keyword must not be incorrectly used. If we provide incorrect arguments, a TypeError will interrupt our program's execution.
Python program that causes error
# The dict built-in must be called with a valid argument.
result = dict(1)Traceback (most recent call last):
File "C:\programs\file.py", line 5, in <module>
result = dict(1)
TypeError: 'int' object is not iterable
Dictionary copy. We can invoke the copy() method on a dictionary to perform a copy. This has the same result as using the dict built-in method.
With this function, we create a powerful dictionary collection from varied arguments. Often with dictionaries we do not need a dict() call. But when we do, dict simplifies our code.