Python 获取求和嵌套字典值的列表

Python 获取求和嵌套字典值的列表,python,python-3.x,list,dictionary,sum,Python,Python 3.x,List,Dictionary,Sum,我试图编写一部分程序,其中用户输入一个目标词(targetWord=input()),分配一个嵌套字典,其键与输入词相同 例如: mainDict = { 'x': {'one': 1, 'blue': 1, 'green' :1}, 'y': {'red': 1, 'blue': 2, 'two': 1}, 'z': {'one': 1, 'green': 1, 'red': 1} } 其中,嵌套字典中的所有值都被赋值为整数 用户可以输入'x',程序将为其分配: ta

我试图编写一部分程序,其中用户输入一个目标词(
targetWord=input()
),分配一个嵌套字典,其键与输入词相同

例如:

mainDict = {
    'x': {'one': 1, 'blue': 1, 'green' :1},
    'y': {'red': 1, 'blue': 2, 'two': 1},
    'z': {'one': 1, 'green': 1, 'red': 1}
}
其中,嵌套字典中的所有值都被赋值为整数

用户可以输入
'x'
,程序将为其分配:

targetDict = mainDict['x']
然后,程序应允许用户再次输入单词,但这一次,输入中的每个单词都会附加到查找列表中,例如用户输入
'y'
,然后
'z'

lookup = ['y', 'z']
然后,程序应该运行嵌套字典,对于每个具有相应键的值(如
targetDict
),只将值附加到新的嵌套列表中,并添加嵌套字典值所包含的任何值。因此,本节的输出应为:

targetOutput = [[2], [1, 1]]
因为在嵌套的dict
'y'
中,只有
'blue'
是一个公共键,它的值
2
被放入一个列表中,然后附加到
targetOutput
上。dict
'z'
的情况相同,其中键
'one'
'green'
都出现在
'x'
'z'
中,将它们的值
1
1
放入嵌套列表中

以下是我的功能失调代码:

targetOutput = []
targetDict = mainDict[targetWord]
for tkey in targetDict:
    tt = []
    for word in lookup:
        for wkey in primaryDict[word]:
            if tkey == wkey:
                tt.append(targetDict[tkey])
tl.append(sum(tt))


print((pl))
最后的sum函数是因为我的最终输出应该是嵌套列表中的值之和,类似于:

tl = [[2], [2]]
我还试图实现相反的效果,在查找中每个键的另一个列表中,它返回一个嵌套列表,其中包含
targetWord
字典也有一个键的每个值的总和,例如:

ll = [[2], [2]]
我的问题是,如何修复代码,使其输出上述两个列表?我对字典很陌生。

字典上的会给你一个,可以像一个集合一样。这意味着您可以获取两个词典的关键视图之间的交集!您需要初始
targetDict
查找中命名的词典之间的交集:

for word in lookup:
    other_dict = mainDict[word]
    common_keys = targetDict.keys() & other_dict
    targetOutput.append([other_dict[common] for common in common_keys])
targetDict.keys()&other_dict
表达式在此处生成交集:

>>> mainDict = {
...     'x': {'one': 1, 'blue': 1, 'green' :1},
...     'y': {'red': 1, 'blue': 2, 'two': 1},
...     'z': {'one': 1, 'green': 1, 'red': 1}
... }
>>> targetDict = mainDict['x']
>>> targetDict.keys() & mainDict['y']
{'blue'}
>>> targetDict.keys() & mainDict['z']
{'green', 'one'}
[other_dict[common]for common in common_key]
列表将获取这些键,并从其他字典中查找它们的值

如果要对值求和,只需将相同的值序列传递给
sum()
函数:

for word in lookup:
    other_dict = mainDict[word]
    common_keys = targetDict.keys() & other_dict
    summed_values = sum(other_dict[common] for common in common_keys)
    targetOutput.append(summed_values)

没有必要将求和值包装到另一个列表中,因为只有一个求和。上面给出的是一个带有
[2,2]
目标输出
列表,而不是
[[2],[2]]

您的问题很难理解。你能\或者某个理解它的人把它重新表述一下吗?@Ev.Kounis我有很多解释要做,对不起。因此,从根本上说,它应该创建两个嵌套列表,其中mainDict中的值与给定targetWord和lookup的键公用的值之和是用户输入。从技术上讲,两个列表最终应该打印相同的内容。