比较嵌套字典中的多个键

时间:2019-06-21 13:06:07

标签: python

假设我有以下嵌套字典:

{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.

3 个答案:

答案 0 :(得分:2)

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

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

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('')

输出准确无误:

  

牛腿:粗
  山羊腿:细长

     

牛尾巴:长
  山羊尾巴:短

     

奶牛:好
  山羊奶:好的

     

牛肉:好吧
  山羊肉:极佳
  鱼肉:很棒

     

鱼鳍:是的

     

鱼骨头:很多

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

您也可以尝试使用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