【问题标题】:Python: merging dictionaries with lists in lists as values and counting themPython:将字典与列表中的列表合并为值并计算它们
【发布时间】:2012-06-14 22:01:24
【问题描述】:

我正在尝试编写一个可以合并两个字典(文本文件!)的程序。这些词典由名词和动词组成,这些名词和动词已被另一个程序从不同的语料库中索引(然后放入文本文件中)。这是这些字典的形式:

dict1 = {'strawberry': [['eat', 1]], 'family-member': [['look up', 1]], 'mall': [['search', 1]]}
dict2 = {'strawberry': [['eat', 1]], 'family-member': [['lose', 1]], 'ovation': [['receive', 1]], 'mall': [['build', 1]]}

如您所见,它们是带有键的字典,在列表中包含值列表。 现在我试图得到这样的输出:

finaldict = {'strawberry': [['eat', 2]], 'family-member': [['look up', 1]['lose',1]], 'mall': [['search', 1]['build', 1]], 'ovation': [['receive', 1]]

到目前为止,我已经能够像这样(在一个字符串中)合并 dict1 和 dict2:

{'strawberry': [['eat', 1]], 'family-member': [['look up', 1]], 'mall': [['search',
1]], 'strawberry': [['eat', 1]], 'family-member': [['lose', 1]], 'ovation':
[['receive', 1]], 'mall': [['build', 1]]}

我使用下一条语句将此字符串转换为字典: finaldict = eval(str1) 它将整个内容变成字典,当我询问 finaldict 的类型时,它也这样说,但它不会将 [['eat', 1]] 之类的语句视为值或任何东西。我需要这个,这样我就可以遍历每个项目并计算它与哪个动词一起出现的次数。

【问题讨论】:

    标签: python dictionary merge


    【解决方案1】:
    from collections import Counter
    
    dict1 = {'strawberry': [['eat', 1]], 'family-member': [['look up', 1]], 'mall': [['search', 1]]}
    dict2 = {'strawberry': [['eat', 1]], 'family-member': [['lose', 1]], 'ovation': [['receive', 1]], 'mall': [['build', 1]]}
    result = {k: Counter(dict(v)) for k, v in dict1.items()}
    for k, v in dict2.items():
        result.setdefault(k, Counter()).update(dict(v))
    
    result = {k: [list(x) for x in v.items()] for k, v in result.items()}
    

    【讨论】:

    • python 的最低版本是多少?
    • 2.7 或 3.1+,dict 理解在 2.7/3.0 中添加,collections.Counter 在 2.7/3.1 中添加。
    【解决方案2】:

    没有什么太花哨的,只是打破它。

    from collections import defaultdict
    
    dict1 = {'strawberry': [['eat', 1]], 'family-member': [['look up', 1]], 'mall': [['search', 1]]}
    dict2 = {'strawberry': [['eat', 1]], 'family-member': [['lose', 1]], 'ovation': [['receive', 1]], 'mall': [['build', 1]]}
    keys = set(dict2.keys()).union(dict1.keys())
    
    final = {}
    for k in keys:
        d1val = dict1.get(k, [])
        d2val = dict2.get(k, [])
    
        resd = defaultdict(lambda: 0)
    
        for word, count in d1val:
            resd[word] += count
    
        for word, count in d2val:
            resd[word] += count
    
        final[k] = [list(i) for i in resd.items()]
    

    【讨论】:

      猜你喜欢
      • 2016-12-22
      • 2017-12-02
      • 2015-01-10
      • 2012-08-11
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多