简体   繁体   中英

sort a dict by a given list of key

I read data from a bunch or emails and count frequency of each word. first construct two counters:

counters.stats = collections.defaultdict(dict)

The key of stats is word. For each word, I construct a dict, whose key is the name of the email and value is the frequency of that word in this email.

Now I have a list which contains those keys in counters.stats, by in a different order. I want to sort the key in 'stats' by the list.

def print_stats(counters):
    for form, cat_to_stats in sorted(counters.stats.items(), key = chi_sort):

How to build the function chi_sort? Or other methods?

Assuming that the values in L only occur once:

D = dict((b,a) for a,b in enumerate(L))
chi_sort = D.get

where L refers to your list.

If this yields the values in reverse order, you can fix that by adding reversed=True to your sorted call.

Use this:

chi_sort = lambda item: your_list_here.index(item[0])

(Replace your_list_here with your list)

Example ( collections.OrderedDict can be replaced by a normal dict ):

>>> import collections
>>> ordereddict = collections.OrderedDict((
...     ('key_78', 'value'),
...     ('key_40', 'value'),
...     ('key_96', 'value'),
...     ('key_53', 'value'),
...     ('key_04', 'value'),
...     ('key_89', 'value'),
...     ('key_52', 'value'),
...     ('key_86', 'value'),
...     ('key_16', 'value'),
...     ('key_63', 'value'),
... ))
>>>
>>> alist = sorted(ordereddict.keys())
>>> alist
['key_04', 'key_16', 'key_40', 'key_52', 'key_53', 'key_63', 'key_78', 'key_86',
 'key_89', 'key_96']
>>> sorted(ordereddict.items(), key=lambda item: alist.index(item[0]))
[('key_04', 'value'), ('key_16', 'value'), ('key_40', 'value'), ('key_52', 'valu
e'), ('key_53', 'value'), ('key_63', 'value'), ('key_78', 'value'), ('key_86', '
value'), ('key_89', 'value'), ('key_96', 'value')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM