Reputation: 11
When given a dictionary(db), is there a way to add values to a key that already exist within the dictionary. Hence the updating or simply adding the key and its value if the key doesn't already exist:
Say that:
db = {'John': [('Brown', 'Blue', 180)]}
def add_anything(db,Name(the key), HairColor(value), EyeColor(value), Height(value):
add_anything(db, "John", "Black", "Red", "160")
and when i updated db, returning db would give back:
{'John': [('Brown', 'Blue', 180),('Black', 'Red', 160)]}
How would that definition function look like? Thank you
Upvotes: 0
Views: 112
Reputation: 1117
Might be missing something here but the faster try/catch (do first then ask forgiveness)?
d = {'John': [('Brown', 'Blue', 180)]}
def add_to_dict(d, k, v):
try:
d[k].append(v)
except KeyError:
d[k] = [v]
return d
print(d)
add_to_dict(d, "John", ('Black', 'Red', 160))
print(d)
add_to_dict(d, "Jim", ('Blond', 'Green', 200))
print(d)
add_to_dict(d, "Jim", ('Blond', 'Green', 220))
print(d)
or the slower if check (ask for permission then do)?
def add_to_dict(d, k, v):
if k in d.keys():
d[k].append(v)
else:
d[k] = [v]
return d
Upvotes: 0
Reputation: 77337
I think the brute force method is the best. Its still short and straight forward
def add_anything(d, key, *value):
if key in d:
if value not in d[key]:
d[key].append(value)
else:
d[key] = [value]
Running a few tests
>>> add_anything(d, 'bob', 'Brown', 'Blue', '180')
>>> d
{'bob': [('Brown', 'Blue', '180')]}
>>> add_anything(d, 'bob', 'Brown', 'Blue', '180')
>>> d
{'bob': [('Brown', 'Blue', '180')]}
>>> add_anything(d, 'bob', 'Brown', 'Blue', '666')
>>> d
{'bob': [('Brown', 'Blue', '180'), ('Brown', 'Blue', '666')]}
>>> add_anything(d, 'jane', 'Brown', 'Blue', '666')
>>> d
{'jane': [('Brown', 'Blue', '666')], 'bob': [('Brown', 'Blue', '180'), ('Brown', 'Blue', '666')]}
Upvotes: 1
Reputation: 36023
Using a set
to prevent duplicates but at the cost of losing order which I'm assuming isn't important:
>>> from collections import defaultdict
>>> db = defaultdict(set)
>>> db['John'].add(('Brown', 'Blue', 180))
>>> db
defaultdict(<type 'set'>, {'John': set([('Brown', 'Blue', 180)])})
>>> db['John'].add(('Brown', 'Blue', 180))
>>> db
defaultdict(<type 'set'>, {'John': set([('Brown', 'Blue', 180)])})
>>> db['John'].add(("Black", "Red", "160"))
>>> db['Jane'].add(("Red", "Gree", "140"))
>>> db
defaultdict(<type 'set'>, {'Jane': set([('Red', 'Gree', '140')]), 'John': set([('Brown', 'Blue', 180), ('Black', 'Red', '160')])})
Upvotes: 0