【问题标题】:create new dictionary based on two existing dictionaries基于两个现有字典创建新字典
【发布时间】:2019-11-17 19:10:37
【问题描述】:

我有两个字典:

d={'doc_1': {'hope': 1, 'court': 2}, 'doc_2': {'hope': 1, 'court': 1}, 'doc_3': {'hope': 1, 'mention': 1}}

count={'doc_1': 6, 'doc_2': 5, 'doc_3': 12}

我只想根据两个字典的相同键将字典 d 的嵌套字典的值与字典 count 的值分开。 预期输出:-

new={{'doc_1': {'hope': 0.16666666, 'court': 0.3333333}, 'doc_2': {'hope': 0.2, 'court': 0.2}, 'doc_3': {'hope': 0.0833333, 'mention': 0.0833333}}。 到目前为止我做了什么:

new={}
for k,v in d.items():
    for p,q in count.items():
        for w,r in v.items():
            if k==p:
                ratio=r/q
                new[k][w]=ratio

这给了我一个错误!!!

【问题讨论】:

    标签: arrays python-3.x dictionary


    【解决方案1】:

    你可以使用dict理解:

    from pprint import pprint
    
    d={'doc_1': {'hope': 1, 'court': 2}, 'doc_2': {'hope': 1, 'court': 1}, 'doc_3': {'hope': 1, 'mention': 1}}
    count={'doc_1': 6, 'doc_2': 5, 'doc_3': 12}
    
    new_d = {k:{kk:vv/count[k] for kk, vv in v.items()} for k, v in d.items()}
    
    pprint(new_d)
    

    打印:

    {'doc_1': {'court': 0.3333333333333333, 'hope': 0.16666666666666666},
     'doc_2': {'court': 0.2, 'hope': 0.2},
     'doc_3': {'hope': 0.08333333333333333, 'mention': 0.08333333333333333}}
    

    【讨论】:

      【解决方案2】:

      关于您的代码,生成错误是因为您尝试设置 new[k][w]new[k] 不存在。要纠正这个问题,您应该将 new[k] 初始化为一个空字典,然后填充它:

      new={}
      for k,v in d.items():
          new[k] = {}
          for p,q in count.items():
              for w,r in v.items():
                  if k==p:
                      ratio=r/q
                      new[k][w]=ratio
      

      输出

      {'doc_1': {'hope': 0.16666666666666666, 'court': 0.3333333333333333},
       'doc_2': {'hope': 0.2, 'court': 0.2},
       'doc_3': {'hope': 0.08333333333333333, 'mention': 0.08333333333333333}}
      

      【讨论】:

      • 感谢提及我的代码中的错误。实际上,我只想在new 空白字典中添加嵌套字典。这就是使用现有键值创建嵌套字典的方式?
      • 是的,嵌套字典是字典中的字典。您可能会看看这个不错的答案:stackoverflow.com/a/16333441/7652544
      猜你喜欢
      • 2017-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      • 2017-08-03
      相关资源
      最近更新 更多