1

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?

ruckarucka
  • 41
  • 2
  • 11

3 Answers3

1

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
pktangyue
  • 8,326
  • 9
  • 48
  • 71
  • Thanks, that makes a lot of sense. This solution worked with one caveat. How would I make it so that the values would only be appended if they key already existed and there were no duplicate values in the dict already? – ruckarucka Nov 13 '17 at 06:57
  • Actually I fixed that issue by simple adding another nested if statement. Thank you! – ruckarucka Nov 13 '17 at 07:00
  • @ruckarucka you're welcome – pktangyue Nov 13 '17 at 07:02
0

In case of an extending the list, you need to access the dict key and append to the existing list:

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)]})

This will check if the item exists in the db, and append if it does. Bye the way, why do you return None? You don't have to return something from the function

Chen A.
  • 10,140
  • 3
  • 42
  • 61
0

You can use setdefault:

def add_name(db, name, gender, year, count, rank=None):
    db.setdefault((name, gender), []).append((year, count, rank))
    return None

or use a defaultdict to begin with:

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
user2390182
  • 72,016
  • 6
  • 67
  • 89