So I have a dictionary "db" which equals
{('ALI', 'MALE'): [(2011, 200, None), (2012, 200, None), (2013, 200, None),
(2014, 200, None), (2015, 200, None)], ('BOB', 'MALE'): [(2012, 200, None),
(2013, 200, None), (2014, 200, None)], ('LUKE', 'MALE'): [(2013, 200, None),
(2015, 200, None)], ('JEFF', 'MALE'): [(2014, 200, None)]}
I need to create a function that takes the database, a name, a gender, a year, a count, and a rank (which may sometimes equal None) and update the dictionary db with the new info. Here is what I have so far.
def add_name(db, name, gender, year, count, rank=None):
db.update({(name, gender): [(year, count, rank)]})
return None
The problem however, is that if I add an item that has a key that already exists in db, say for example "('BOB','MALE')", the .update method will overwrite the values associated with that key and replace them with the values from the function.
In the event of keys that overlap, how can I simply append the values instead?
答案 0 :(得分:0)
try this:
def add_name(db, name, gender, year, count, rank=None):
# check if the key (name, gender) in db. if it's in, append
if (name, gender) in db:
db[(name, gender)].append((year, count, rank))
# else new a key
else:
db[(name, gender)] = [(year, count, rank)]
return None
答案 1 :(得分:0)
如果要扩展列表,您需要访问dict键并附加到现有列表:
def add_name(db, name, gender, year, count, rank=None):
if (db, name) in db:
db[(name, gender)].append((year, count, rank))
else:
db.update({(name, gender): [(year, count, rank)]})
这将检查数据库中是否存在该项目,如果存在,则追加该项目。
再见,你为什么要回归None
?你不必从函数
答案 2 :(得分:0)
您可以使用setdefault
:
def add_name(db, name, gender, year, count, rank=None):
db.setdefault((name, gender), []).append((year, count, rank))
return None
或使用defaultdict
开头:
from collections import defaultdict
db = defaultdict(list)
def add_name(db, name, gender, year, count, rank=None):
db[(name, gender)].append((year, count, rank))
return None