C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: We add a key "cat" to the dictionary with a value of 1. Then we use get() to print this value.
Python program that uses dict
# Use dict to create empty dictionary.
values = dict()
# Add value and get value.
values["cat"] = 1
print(values.get("cat"))
Output
1
Tip: When we modify the copied dictionary, the original dictionary is left unchanged. The two are separate in memory.
Python program that copies with dict built-in
values = {"cat": 1, "bird": 2}
# Copy the dictionary with the dict copy constructor.
copy = dict(values)
# Change copy.
copy["cat"] = 400
# The two dictionaries are separate.
print(values)
print(copy)
Output
{'bird': 2, 'cat': 1}
{'bird': 2, 'cat': 400}
Python program that creates list with dict
# 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(values)
print(lookup.get("cat"))
print(lookup.get("bird"))
Output
[('cat', 1), ('bird', 200)]
1
200
Python program that uses named arguments
# Create a dictionary with named arguments.
animals = dict(bird=1, dog=2, fish=9)
print(animals.get("bird"))
print(animals.get("dog"))
print(animals.get("fish"))
Output
1
2
9
Python program that causes error
# The dict built-in must be called with a valid argument.
result = dict(1)
Output
Traceback (most recent call last):
File "C:\programs\file.py", line 5, in <module>
result = dict(1)
TypeError: 'int' object is not iterable