【问题标题】:Python 3.6 merge dictionaries failsPython 3.6 合并字典失败
【发布时间】:2017-04-11 10:05:40
【问题描述】:

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

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 上会失败。

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    dict(**x, **y)doing what its supposed to do。通过用第二个 arg 覆盖第一个 arg 的值来创建 bigdict。您需要自己总结这些值。

    您可以使用Counter

    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}
    

    【讨论】:

    • 感谢您的回答+链接。帮了大忙。
    猜你喜欢
    • 1970-01-01
    • 2016-03-08
    • 2019-04-18
    • 2019-02-03
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多