简体   繁体   中英

Sorting nested dictionaries Python, lambda not working?

I have a dictionary of dictionaries based on {month:{id:value,id:value},month:{id:value,id:value}} like this

{9: {10: 1, 4113: 1, 533: 2, 4124: 2, 31: 1, 7713: 1, 12038: 1, 550: 3, 10794: 1, 15922: 1, 4671: 1, 65: 2, 4681: 1, 8789: 1, 1622: 1, 1116: 2, 605: 2, 8992: 1, 614: 2, 1639: 2, 17515: 1, 4883: 1}, 8: {4103: 1, 12298: 2, 19: 1, 4126: 1, 32: 2, 4129: 3, 6180: 1, 6192: 1, 51: 5, 52: 1, 53: 1, 58: 1}...etc

and I'm trying to sort the value so that I can print the highest values for each month like august(8) highest value for august... sept(9) highest value for sept.. and so on.

I tried using lambda like in many of the StackOverflow questions on this but it hasn't worked. I get a Key error .

newlist9= sorted(aid2tagM.items(),key=lambda x: x[0][1], reverse=True)

For the input you have given,

[(month, sorted(data.items(), key=lambda x:-x[1])) for month, data in d.items()]

produces

[(8,
  [(51, 5),
   (4129, 3),
   (12298, 2),
   (32, 2),
   (4103, 1),
   (19, 1),
   (4126, 1),
   (6180, 1),
   (6192, 1),
   (52, 1),
   (53, 1),
   (58, 1)]),
 (9,
  [(550, 3),
   (533, 2),
   (4124, 2),
   (65, 2),
   (1116, 2),
   (605, 2),
   (614, 2),
   (1639, 2),
   (12038, 1),
   (10, 1),
   (4113, 1),
   (4883, 1),
   (31, 1),
   (8992, 1),
   (7713, 1),
   (10794, 1),
   (15922, 1),
   (4671, 1),
   (4681, 1),
   (8789, 1),
   (1622, 1),
   (17515, 1)])]

It looks like you may be treating the dictionaries as lists in the lambda expression. The term

lambda x:x[0][1]

looks like a 2 dimensional list index. However your data structure is nested dictionaries. So unless you have a guaranteed entry for key 0 for every top level dictionary (assuming it is the month of year) and a guaranteed key 1 in every sub-level dictionary it will give you a key error. A suggestion to try:

for month in range(1,12+1):
    month_to_sort = aid2tagM[month]
    month_keys = month_to_sort.keys()   
    month_keys.sort(reverse=True)

    monthly_data_sorted_by_key = []
    for month_key in month_keys:
        print month,month_key,aid2tag[month][month_key]
        monthly_data_sorted_by_key.append([month_key,aid2tag[month][month_key]])

This will give you each month sorted by the keys of the nested dictionary.

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