打印字典键的每个组合的列表以及右侧的键值的相关总和

Print a list of every combination of dictionary keys with the associated sum of the key values to the right

我有几个词典,我想打印一个 table,其中每一行都是所有词典中键的唯一组合。对于每一行,我还想打印该特定组合中键值的总和。

所以,如果我有这些词典:

dict1 = {"Main": 8, "Optional": 6, "Obscure": 4}
dict2 = {"Global": 8, "Regional": 4, "Local": 2}
...

输出看起来像这样(按总和从高到低排序):

Main, Global, 16
Optional, Global, 14
Main, Regional, 12
Obscure, Global, 12
Main, Local, 10
Optional, Regional, 10
Optional, Local, 8
Obscure, Regional, 8
Obscure, Local, 6

根据我的阅读,itertools.product 将是我正在寻找的内容,但是现有问题中的 none 是我的用例,我什至正在努力开始.

如有任何帮助,我们将不胜感激。

谢谢

我想这应该是这样的:

import itertools

dict1 = {"Main": 8, "Optional": 6, "Obscure": 4}
dict2 = {"Global": 8, "Regional": 4, "Local": 2}

merged = {'{}, {}'.format(prod[0], prod[1]): dict1[prod[0]] + dict2[prod[1]] 
          for prod in itertools.product(dict1, dict2)}

for k, v in merged.items():
    print('{}: {}'.format(k, v))

输出:

Optional, Regional: 10
Main, Regional: 12
Optional, Local: 8
Main, Global: 16
Optional, Global: 14
Main, Local: 10
Obscure, Regional: 8
Obscure, Global: 12
Obscure, Local: 6

在字典 items() 上使用 itertools 中的 product 可以同时获取键和值,并且通过键值对的组合可以构造最终结果非常直接:

from itertools import product
sorted([(k1, k2, v1+v2) for (k1, v1), (k2, v2) in product(dict1.items(), dict2.items())], \
       key = lambda x: x[2], reverse=True)

# [('Main', 'Global', 16),
#  ('Optional', 'Global', 14),
#  ('Obscure', 'Global', 12),
#  ('Main', 'Regional', 12),
#  ('Main', 'Local', 10),
#  ('Optional', 'Regional', 10),
#  ('Obscure', 'Regional', 8),
#  ('Optional', 'Local', 8),
#  ('Obscure', 'Local', 6)]

您没有看错。只需添加 sorted():

from itertools import product
from operator import itemgetter

results = [(k1, k2, dict1[k1] + dict2[k2])
           for k1, k2 in product(dict1.keys(), dict2.keys())]

for k1, k2, sum_ in sorted(results, key=itemgetter(2), reverse=True): 
    print(k1, k2, sum_, sep=', ')

构建此方法是为了支持可变数量的词典。您将字典传递给 get_product_sums() 方法,该方法然后从字典元组创建笛卡尔积。

然后我们遍历我们的新 subitem 来计算总和,方法是在我们的 flattened 中查找,现在它只是一个一维字典。然后我们按总和排序,return 最终 result.

的排序元组列表
from itertools import product

def get_product_sums(* args):
    result = []
    flattened = {k:v for d in args for k, v in d.items()}
    for subitem in product(* args, repeat=1):
        data = subitem + (sum(flattened[key] for key in subitem),)  
        result.append(data)
    return sorted(result, key=lambda x: x[-1], reverse=True)

示例输出:

>>> dict1 = {"Global": 8, "Regional": 4, "Local": 2} 
>>> dict2 = {"Main": 8, "Optional": 6, "Obscure": 4}
>>> for item in get_product_sums(dict1, dict2):
...     print ', '.join(str(element) for element in item)
Global, Main, 16
Global, Optional, 14
Global, Obscure, 12
Regional, Main, 12
Local, Main, 10
Regional, Optional, 10
Local, Optional, 8
Regional, Obscure, 8
Local, Obscure, 6