Reputation: 187
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
Upvotes: 2
Views: 6033
Reputation: 140549
Because of the requirement to return all members of a tie, you have to keep track of all the possibilities.
def artist_with_most_work(db):
keys_by_size = collections.defaultdict(list)
maxsize = 0
for key, recordlist in db.items():
nitems = len(recordlist)
keys_by_size[nitems].append(key)
maxsize = max(maxsize, nitems)
return keys_by_size[maxsize]
Upvotes: 0
Reputation: 1121654
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']
Upvotes: 6