python 2.7 - Given three nested dictionaries, sort the top two nested dictionaries from a value in the innermost dictionary? -
i trying sort both outermost dictionary , "middle" dictionary value of "cal" (highest first) in innermost dictionary. accomplish using ordereddict.
given example below, trying accomplish:
- for foods, order food subtypes highest calorie content (i.e - pizza, pesto should appear first because has higher calories when compared cheese.
- order foods highest calorie content (i.e - pizza should appear first has subtype more calories other food)
i have following data:
foods = { "apple": { "red": { "cal": "1", "taste": "4" }, "green": { "cal": "2", "taste": "6" } }, "pizza": { "pesto": { "cal": "200", "taste": "9" }, "cheese": { "cal": "100", "taste": "11" } } }
this result looking for:
d = { "pizza": { "pesto": { "cal": "200", "taste": "9" }, "cheese": { "cal": "100", "taste": "11" } }, "apple": { "green": { "cal": "2", "taste": "6" }, "red": { "cal": "1", "taste": "4" } } }
this should work:
from collections import ordereddict od = ordereddict() food, dct in sorted(foods.items(), key=lambda x: max(int(y['cal']) y in x[1].values()), reverse=true): od[food] = ordereddict() subod = od[food] subkey, subdct in sorted(dct.items(), key=lambda x: int(x[1]['cal']), reverse=true): subod[subkey] = subdct
with new input gives:
# pprint import pprint # pprint(od) ordereddict([('cheesecake', ordereddict([('extrasweet', {'cal': '18000', 'taste': '16'}), ('sweet', {'cal': '12000', 'taste': '17'})])), ('icecream', ordereddict([('chocolate', {'cal': '2000', 'taste': '9'}), ('vanilla', {'cal': '1000', 'taste': '11'})])), ('pizza', ordereddict([('pesto', {'cal': '200', 'taste': '9'}), ('cheese', {'cal': '100', 'taste': '11'})])), ('apple', ordereddict([('green', {'cal': '20', 'taste': '6'}), ('red', {'cal': '1', 'taste': '4'})]))])
(but please: next question take tour, read on how ask question , provide minimal, complete , verifiable example.)
Comments
Post a Comment