Say I have a dictionary that looks like this:
mappings = {"some_key": 3}
or it could look like this:
mappings = {"some_key": [4,5,6]}
Say I have a value 100 and a key of "some_key" in this function:
def add_to_mappings(key, value):
if key in mappings:
mappings[key] = ?
and I either want to add to the list if it exists or create one if it does not. At the end, I want my mappings to look like either:
mappings = {"some_key": [3, 100]}
or
mappings = {"some_key": [4,5,6,100]}
Without defaultdict
:
mappings = dict()
def add_to_mappings(key, value):
try:
mappings[key].append(100)
except KeyError:
mappings[key] = [100]
With defaultdict
:
from collections import defaultdict
mappings = defaultdict(list)
def add_to_mappings(key, value):
mappings[key].append(value)
Edit: I misunderstood the original requirements, to take an item if it already existed and create a list out of it and the new item, then the first example could be changed to this:
mappings = dict(foo=3)
def add_to_mappings(key, value):
try:
mappings[key].append(100)
except KeyError:
mappings[key] = [100]
except AttributeError:
mappings[key] = [mappings[key], value]
add_to_mappings("foo", 5)
# mappings ==> { "foo": [3, 5] }
You check if something is a list with isinstance(x, list)
. You can extract existing values from a dictionary and replace the value with simple assignment. So:
def add_to_mappings(d, key, value): # Remember to pass in the dict too!
if key in d:
# The value is present
v = d[k]
if isinstance(v, list):
# Already a list: just append to it
v.append(value)
else:
# Not a list: make a new list
d[k] = [v, value]
else:
# Not present at all: make a new list
d[key] = [value]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With