Python 3.6 合并字典失败

标签 python python-3.x dictionary

我正在尝试合并两个字典,在搜索关于堆栈溢出的关闭问题后,我找到了下一个解决方案:

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/

相关文章:

Python 不稳定行为 :/usr/bin/python: No module named hotspotd. hotspotd

java - 在 Java 中寻找 "chained map"实现

java - 要映射的计时器类

python - pyinstaller导入错误: No module name '_socket'

python - Virtualenv 不能继承 GetSitePackages() 属性

即使安装了Python模块也找不到错误

python - 在 SQLAlchemy 中定义表时,如何将函数(依赖于其他列的表达式)定义为列的默认值?

python - 使用随机生成的变量对函数进行 doctest

python-3.x - 无法在 Windows Python 3.5 上安装 Levenshtein distance 包

python - ast.literal_eval 用于 python 中的变量?