繁体   English   中英

比较嵌套字典中的多个键

[英]Comparing multiple keys in a nested dictionary

假设我有以下嵌套字典:

{Cow:{legs:thick, tail:long, milk:good, meat:alright}, Goat:{legs:slender, tail:short, milk:ok, meat:excellent}, Fish:{fins:yes, meat:superb, bones:plenty}}

我的目标是比较外键(牛,山羊和鱼),并检查它们的内键是否匹配。 理想情况下,我应该得到:

Cow legs: thick 
Goat legs: slender

Cow tail: long
Goat tail: short

Cow milk: good 
Goat milk: ok

Cow meat: alright
Goat meat: excelent
Fish meat: superb

Fish fins: yes
Fish bones: plenty

对我来说,问题是我还无法弄清楚如何比较多个词典中的内键。

我可以按照传统方式打开嵌套字典的包装:

for outerkeys, innerdicts in nestedDict:
      #but here I'm stuck on how to process multiple inner dictionaries
      #to extract matching (and unmatching) keys.

首先,您要按“类别”(例如“腿”,“尾巴”,“肉”)分组,这是内部词典的关键。

然后您可以迭代新词典并以所需格式列出输出:

from collections import defaultdict

in_dic = {"Cow": {"legs": "thick", "tail": "long", "milk": "good", "meat": "alright"},
          "Goat": {"legs": "slender", "tail": "short", "milk": "ok", "meat": "excellent"},
          "Fish": {"fins": "yes", "meat": "superb", "bones": "plenty"}}


result_by_category = defaultdict(list)

for animal, categories in in_dic.items():
    for category, value in categories.items():
        result_by_category[category].append((animal, value))

for category, values in result_by_category.items():
    for animal, value in values:
        print('{} {}: {}'.format(animal, category, value))
    print('')

输出是确切的:

牛腿:粗
山羊腿:纤细

牛尾巴:长
山羊尾巴:短

牛奶:好
山羊奶:可以

牛肉:好
山羊肉:极好
鱼肉:精湛

鱼鳍:是的

鱼骨头:充足

您可以通过使用理解力构建带有重组键/值的列表来做到这一点:

animals = {"Cow": {"legs": "thick", "tail": "long", "milk": "good", "meat": "alright"},
          "Goat": {"legs": "slender", "tail": "short", "milk": "ok", "meat": "excellent"},
          "Fish": {"fins": "yes", "meat": "superb", "bones": "plenty"}}

triples   = [(trait,animal,value) for animal,traits in animals.items() for trait,value in traits.items()]

lineBreak = {min(triples)[0]}
for trait,animal,value in sorted(triples):
    if not(trait in lineBreak or lineBreak.add(trait)): print("")
    print(f"{animal} {trait}: {value}")

...

Fish bones: plenty

Fish fins: yes

Cow legs: thick
Goat legs: slender

Cow meat: alright
Fish meat: superb
Goat meat: excellent

Cow milk: good
Goat milk: ok

Cow tail: long
Goat tail: short

您也可以尝试使用grouby

from itertools import groupby
from operator import itemgetter

nested_dict = {
    "Cow": {"legs": "thick", "tail": "long", "milk": "good", "meat": "alright"},
    "Goat": {"legs": "slender", "tail": "short", "milk": "ok", "meat": "excellent"},
    "Fish": {"fins": "yes", "meat": "superb", "bones": "plenty"},
}

refactored_items = (
    (k1, k2, v2) for k1, v1 in nested_dict.items() for k2, v2 in v1.items()
)
sorted_refactored_items = sorted(refactored_items, key=itemgetter(1))
for _, g in groupby(sorted_refactored_items, key=itemgetter(1)):
    print("\n".join(f"{a} {b}: {c}" for a, b, c in g))
    print("")

输出:

Fish bones: plenty

Fish fins: yes

Cow legs: thick
Goat legs: slender

Cow meat: alright
Goat meat: excellent
Fish meat: superb

Cow milk: good
Goat milk: ok

Cow tail: long
Goat tail: short

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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