get - default value of a non existing key while accessing¶Especially handy if you're unsure about the presence of a key.
my_dict = {"a": 1, "b": 2, "c": 3}
Don't do it like this.
if "g" in my_dict:
value = my_dict["g"]
else:
value = "some default value"
print(value)
some default value
Or like this.
try:
value = my_dict["g"]
except KeyError:
value = "some default value"
print(value)
some default value
value = my_dict.get("g", "some default value")
print(value)
some default value
Note that if you don't provide the default value for get, the return value will be None if the key is not present in the dictionary
value = my_dict.get("g")
print(value is None)
True
setdefault - same as get but also sets the value if not present¶Don't do it like this.
my_dict = {"a": 1, "b": 2, "c": 3}
key = "g"
if key in my_dict:
value = my_dict[key]
else:
value = "some default value"
my_dict[key] = value
print(value)
print(my_dict)
some default value
{'a': 1, 'b': 2, 'c': 3, 'g': 'some default value'}
my_dict = {"a": 1, "b": 2, "c": 3}
key = "g"
value = my_dict.setdefault(key, "some default value")
print(value)
print(my_dict)
some default value
{'a': 1, 'b': 2, 'c': 3, 'g': 'some default value'}
Let's say we have a collection of numbers and we want to store those as a dictionary where the number is key and it's square is the value.
numbers = (1, 5, 10)
Don't do it like this.
squares = {}
for num in numbers:
squares[num] = num**2
print(squares)
{1: 1, 5: 25, 10: 100}
squares = {num: num**2 for num in numbers}
print(squares)
{1: 1, 5: 25, 10: 100}
keys = ("a", "b", "c")
values = [True, 100, "John Doe"]
Don't do it like this.
my_dict = {}
for idx, key in enumerate(keys):
my_dict[key] = values[idx]
print(my_dict)
{'a': True, 'b': 100, 'c': 'John Doe'}
my_dict = {k: v for k, v in zip(keys, values)}
print(my_dict)
# Or even like this:
my_dict2 = dict(zip(keys, values))
assert my_dict2 == my_dict
{'a': True, 'b': 100, 'c': 'John Doe'}
my_dict = {"age": 83, "is gangster": True, "name": "John Doe"}
Don't do it like this.
for key in my_dict:
val = my_dict[key]
print(f"key: {key:15s} value: {val}")
key: age value: 83 key: is gangster value: True key: name value: John Doe
for key, val in my_dict.items():
print(f"key: {key:15s} value: {val}")
key: age value: 83 key: is gangster value: True key: name value: John Doe