Sort dictionary of lists by key value pairs

You could flatten the dictionary (d here) into a list of tuples with the corresponding key/value pairs, and sort the tuples according to the values:

from operator import itemgetter

l = [(k,i) for k,v in d.items() for i in v]
# [('fbi', 229), ('fbi', 421), ('fbi', 586), ('fbi', 654),...
list(zip(*sorted(l, key=itemgetter(1))[:3]))[0]
# ('hillary', 'hillary', 'fbi')

you could

  1. invert your mapping, creating a dictionary with numbers => list of names
  2. sort this dictionary (as tuple)
  3. pick the 3 first items

like this:

import collections

d = collections.defaultdict(list)
data = {'fbi': [229, 421, 586, 654, 947, 955, 1095, 1294, 1467, 2423, 3063, 3478, 3617, 3730, 3848, 3959, 4018, 4136, 4297, 4435, 4635, 4679, 4738, 5116, 5211, 5330, 5698, 6107, 6792, 6906, 7036], 'comey': [605, 756, 1388, 1439, 1593, 1810, 1959, 2123, 2506, 3037, 6848], 'hillary': [14, 181, 449, 614, 704, 1079, 1250, 2484, 2534, 2659, 3233, 3374, 3488, 3565, 4076, 4756, 4865, 6125, 7109]}

for k,vlist in data.items():
    for v in vlist:
        d[v].append(k)

result = [v[0] for k,v in sorted(d.items())[:3]]

print(result)

this prints:

['hillary', 'hillary', 'fbi']

note that if there are several names attached to a value, this code will pick only the first one (v[0])


Just use lambda function in sorted().

l = [(k,i) for k,v in d.items() for i in v]
res = [v[0] for v in sorted(l, key=lambda x: x[1])][:20]