Python 2.7.12 - 替换嵌套在另一个字典中的列表中的字典键

Python 2.7.12 - Replacing dictionary keys from a list nested in another dictionary

我有 2 部字典,描述了不同地方的物品类别和物品价值

categories = {'CAT1':['A','B','C'],'CAT2':['D','E','F']
items = {'A':[1.0],'B':[2.5, 1.0], 'C':[2.0], 'D':[0.2, 0.4], 'E':[0.1], 'F':[2.2, 2.4]}

我需要第三个字典来提供按类别分组和排序的项目的值,例如:

new_dict = {'CAT1':[1.0, 2.5, 1.0, 2.0], 'CAT2':[0.2, 0.4, 0.1, 2.2, 2.4]}

我搜索了现有的问题,但无法解决任何问题。在这方面太菜鸟了。

使用以下方法:

result = {k: [item for i in sorted(items) if i in v for item in items[i]] 
             for k,v in categories.items()}
print(result)

输出:

{'CAT2': [0.2, 0.4, 0.1, 2.2, 2.4], 'CAT1': [1.0, 2.5, 1.0, 2.0]}

据我所知,您的 "sorting" 结果来自类别字典中原始项目的顺序。

首先迭代类别字典的键和值:

result = {}
for cat, entries in categories.items(): # cat='CAT1', ent=['A', 'B', 'C']

最简单的方法是使用 defaultdict。但是您现在可以用一个空列表填充生成的字典。

    result[cat] = []

现在,遍历条目列表:

    for entry in entries: # 'A', 'B', 'C'

条目列表中的每个 entry 都是您提供的 items 词典的关键字,因此请查找:

        ent_items = items[entry]  # ent_items = [1.0]

该查找 (ent_items) 的结果是一个浮点数列表。将其连接到结果字典中的正确列表:

        result[cat] += ent_items   # result['CAT1'] = [1.0]

请注意,我没有对任何内容进行排序,因为您的示例似乎没有对任何内容进行排序。字典键(类别)的顺序无关紧要,其他一切都由列表中项目的顺序决定。