我正在尝试合并两个字典,在搜索关于堆栈溢出的关闭问题后,我找到了下一个解决方案:
mergeDicts = {**dict1, **dict2}
但这行不通。虽然我知道我的代码没问题,因为我观察到单个字典的正确结果,但一旦合并,我就得不到正确的结果
def readFiles(path1):
// count words
if __name__ == '__main__':
a = readFiles('C:/University/learnPy/dir')
b = readFiles('C:/Users/user/Anaconda3/dir')
bigdict = {**a, **b}
print(a['wee'])
print(b['wee'])
print(bigdict['wee'])
在 a
中有 1 个 .txt
文件包含 2 wee
在 b
中有 1 个 .txt
文件包含 1 wee
所以我希望 bigdict 输出为 3,但我观察到 bigdict 只是获取第一个 dict 的数字。 {**dict1 (THIS ONE), **dict2}
合并无效。
问题:出了什么问题?为什么这在 python 3.6 上失败,而答案表明它应该工作。
最佳答案
dict(**x, **y)
是 doing what its supposed to do .通过用第二个参数覆盖第一个参数的值来创建 bigdict
。您需要自己总结这些值。
您可以使用计数器
from collections import Counter
a = {'wee':1, 'woo':2 }
b = {'wee':10, 'woo': 20 }
bigdict = dict(Counter(a)+Counter(b))
Out[23]: {'wee': 11, 'woo': 22}
关于Python 3.6 合并字典失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43335309/