给定三个嵌套字典,从最里面的字典中的值中排序前两个嵌套字典?

时间:2017-08-18 07:02:40

标签: python-2.7

我正在尝试对最外层字典和"中间"进行排序。字典按" Cal"的值(最高的第一个)在最里面的字典中。我想用OrderedDict完成这个。

鉴于以下示例,我正在努力实现这一目标:

  • 对于所有食物,按最高卡路里含量订购食物亚型(即 - 对于比萨饼,Pesto应该首先出现,因为它与奶酪相比具有更高的卡路里。
  • 按最高卡路里含量订购所有食物(即 - 披萨应首先出现,因为它的卡路里含有的卡路里比其他任何食物都多)

我有以下数据:

d =
{
    "Pizza": {
        "Pesto": {
            "Cal": "200", 
            "Taste": "9"
        }, 
        "Cheese": {
            "Cal": "100", 
            "Taste": "11"       
        }
    }, 
    "Apple": {
        "Green": {
            "Cal": "2", 
            "Taste": "6"
        }, 
        "Red": {
            "Cal": "1", 
            "Taste": "4" 
        }       
    }
}

这是我要找的结果:

ismember

2 个答案:

答案 0 :(得分:0)

这应该有效:

from collections import OrderedDict

od = OrderedDict()
for food, dct in sorted(foods.items(),
                        key=lambda x: max(int(y['Cal']) for y in x[1].values()),
                        reverse=True):
    od[food] = OrderedDict()
    subod = od[food]
    for subkey, subdct in sorted(dct.items(), key=lambda x: int(x[1]['Cal']),
                                 reverse=True):
        subod[subkey] = subdct

用你的新输入给出:

# from 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'})]))])

(但请:为了您的下一个问题,请转到tour,阅读how to ask a question并提供minimal, complete and verifiable example。)

答案 1 :(得分:0)

我能够以非pythonic的方式解决它。这是重写的问题和解决方案。如果有人想试一试,我会感谢一个更简单的解决方案。

import json
from collections import OrderedDict
from operator import itemgetter

foods = {
    "Apple": {
        "Red": {
            "Cal": "1", 
            "Taste": "4"
        }, 
        "Green": {
            "Cal": "20", 
            "Taste": "6"       
        }
    }, 
    "Pizza": {
        "Pesto": {
            "Cal": "200", 
            "Taste": "9"
        }, 
        "Cheese": {
            "Cal": "100", 
            "Taste": "11" 
        }       
    },
    "Cheesecake": {
        "Sweet": {
            "Cal": "12000", 
            "Taste": "17"
        }, 
        "ExtraSweet": {
            "Cal": "18000", 
            "Taste": "16" 
        }       
    },
    "IceCream": {
        "Chocolate": {
            "Cal": "2000", 
            "Taste": "9"
        }, 
        "Vanilla": {
            "Cal": "1000", 
            "Taste": "11" 
        }       
    }
}

foodDict = {}
foodTypeDict = {}
ary = []

# This orders the food types for each food 

for food in foods.iteritems():
    foodTypeDict[food[0]] = OrderedDict(sorted(food[1].iteritems(), key=lambda x: x[1]['Cal'],reverse=True))

# This orders the entire dictionary of food 

for food,value in foodTypeDict.iteritems():
    for a in value.iteritems():
        ary.append(a[1]['Cal'])
    foodDict[food] = float(max(ary))
    ary = []

sFoodDict = OrderedDict(sorted(foodDict.iteritems(), key=lambda x:x[1], reverse=True))

# Create final dictionary with contents of former two dictionaries

for a in sFoodDict.items():
    sFoodDict[a[0]] = foodTypeDict[a[0]]

print(json.dumps(sFoodDict,indent=4))
相关问题