n00bprogrammer22 n00bprogrammer22 - 19 days ago 6
Python Question

Finding key(s) with most values in dictionary

I'm working on a function where I need to find the keys (of artists names) in a dictionary that have the most values. Sometimes two keys have the same number of values and in that case I need to return a list of the artists names.

Example Dictionary:

{'M':[("One",1400,30.0, 20.5,"oil paint","Austria"),("Three",1430,100.0,102.0,"watercolor","France")],
'P':[("Eight",1460, 225.0, 200.0, "fresco","Netherlands")],
'U':[("Nine",1203,182.0, 957.0,"egg tempera","Italy"), ("Twelve",1200,76.2,101.6,"egg tempera","France")]
}


For this dictionary since M and U have the most values (M has 2 and U has 2 while P only has 1) the function should return

artists_with_most_work(dictionary1())

['M', 'U']


How could I search for the number of values of each keys and return the ones that have the most? I figured using max() would be a good idea but I don't think I'm using it correctly in my current attempt below. Thanks to anyone who can help

Code:

def artist_with_most_work(db):
matches = []
for key, record_list in db.items():
for record in record_list:
if item in record:
max(db) = themax
matches.append(themax)
return matches

Answer

You'll have to first find the maximum length, then return all keys that reference a list with that length:

def artist_with_most_work(db):
    maxcount = max(len(v) for v in db.values())
    return [k for k, v in db.items() if len(v) == maxcount]

Demo:

>>> def artist_with_most_work(db):
...     maxcount = max(len(v) for v in db.values())
...     return [k for k, v in db.items() if len(v) == maxcount]
...
>>> d1 = {'M':[("One",1400,30.0, 20.5,"oil paint","Austria"),("Three",1430,100.0,102.0,"watercolor","France")],
...       'P':[("Eight",1460, 225.0, 200.0, "fresco","Netherlands")],
...       'U':[("Nine",1203,182.0, 957.0,"egg tempera","Italy"), ("Twelve",1200,76.2,101.6,"egg tempera","France")]
...      }
>>> artist_with_most_work(d1)
['M', 'U']
Comments