【问题标题】:Update dictionary inside of dictionary when key is already present当键已经存在时更新字典内部的字典
【发布时间】:2020-05-27 15:07:47
【问题描述】:

我知道这个问题已经存在多种变体,并且我已经研究过了。具体来说,我遇到的问题是herehere。我已经尝试使用列出的所有解决方案,但它确实对我不起作用,因为在我的情况下,我必须遍历另一个字典,而且很多时候 dict 的 dict 中的键也是相同的(在这种情况下value 应该变成一个列表。我举个例子来说明:

假设entity_sentiment_dictionary 是我想从entity_sentiment_int_int_dict 附加到的字典

entity_sentiment_dictionary = {  'name': {'userid1': 0.0},
 'Aditya': {'userid1': 0.0},
 'Glen': {'5dad13fc54aeb500078637e0': -0.10000000149011612},
 'Kenta': {'5dad13fc54aeb500078637e0': 0.0},
 'Keita': {'5dd23a18c7949300087d8d88': 0.0},
 'Ganchan': {'5dd23a18c7949300087d8d88': 0.0},
 'Anna': {'5dd23a18c7949300087d8d88': 0.0},
 'Joe': {'5dd23a18c7949300087d8d88': 0.8999999761581421}}

entity_sentiment_int_int_dict = {  'name': {'userid1': 0.1},
                                  'Aditya': {'userid2': 0.3}}

当我更新时,结果应该是这样的:

entity_sentiment_dictionary = {  'name': {'userid1': [0.0,0.1]},
     'Aditya': {'userid1': 0.0, 'userid2': 0.3},
     'Glen': {'5dad13fc54aeb500078637e0': -0.10000000149011612},
     'Kenta': {'5dad13fc54aeb500078637e0': 0.0},
     'Keita': {'5dd23a18c7949300087d8d88': 0.0},
     'Ganchan': {'5dd23a18c7949300087d8d88': 0.0},
     'Anna': {'5dd23a18c7949300087d8d88': 0.0},
     'Joe': {'5dd23a18c7949300087d8d88': 0.8999999761581421}}

这是我在尝试了所有可以在网上找到的方法后所达到的目标:

for key in entity_sentiment_int_int_dict.keys():
        if key in entity_sentiment_dictionary:
            for k in entity_sentiment_dictionary.keys():
                if key==k:
                    entity_sentiment_dictionary[key][k] = dict(entity_sentiment_int_int_dict[key])
        else:
            entity_sentiment_dictionary[key] = entity_sentiment_int_int_dict[key]

它产生了我的结果:

{'name': {'usedid1': 0.0,'name': {'userid1': 0.1}},
 'Aditya': {'userid1': 0.0, 'Aditya': {'userid2': 0.5} },
 'Glen': {'5dad13fc54aeb500078637e0': -0.10000000149011612},
 'Kenta': {'5dad13fc54aeb500078637e0': 0.0},
 'Keita': {'5dd23a18c7949300087d8d88': 0.0},
 'Ganchan': {'5dd23a18c7949300087d8d88': 0.0},
 'Anna': {'5dd23a18c7949300087d8d88': 0.0},
 'Joe': {'5dd23a18c7949300087d8d88': 0.8999999761581421}}

我觉得我快到了,需要对嵌套的 for 循环进行更改。感谢您提供任何帮助,并建议使用任何其他方式来获得预期结果。

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    这里有一个解决方案:

    for k, v in entity_sentiment_int_int_dict.items():
        if k in entity_sentiment_dictionary.keys():
            entry = entity_sentiment_dictionary[k]
            for update_key, update_val in v.items():
                if update_key in entry:
                    if isinstance(entry[update_key], list):
                        entry[update_key].append(update_val)
                    else:
                        entry[update_key] = [entry[update_key], update_val]
                else:
                    entry[update_key] = update_val
    
    # with 'out' as desired output dict from OP:
    entity_sentiment_dictionary == out  # True
    

    完整的代码重现:

    entity_sentiment_dictionary = {  'name': {'userid1': 0.0},
     'Aditya': {'userid1': 0.0},
     'Glen': {'5dad13fc54aeb500078637e0': -0.10000000149011612},
     'Kenta': {'5dad13fc54aeb500078637e0': 0.0},
     'Keita': {'5dd23a18c7949300087d8d88': 0.0},
     'Ganchan': {'5dd23a18c7949300087d8d88': 0.0},
     'Anna': {'5dd23a18c7949300087d8d88': 0.0},
     'Joe': {'5dd23a18c7949300087d8d88': 0.8999999761581421}}
    
    entity_sentiment_int_int_dict = {  'name': {'userid1': 0.1},
                                      'Aditya': {'userid2': 0.3}}
    
    out = {'name': {'userid1': [0.0,0.1]},
         'Aditya': {'userid1': 0.0, 'userid2': 0.3},
         'Glen': {'5dad13fc54aeb500078637e0': -0.10000000149011612},
         'Kenta': {'5dad13fc54aeb500078637e0': 0.0},
         'Keita': {'5dd23a18c7949300087d8d88': 0.0},
         'Ganchan': {'5dd23a18c7949300087d8d88': 0.0},
         'Anna': {'5dd23a18c7949300087d8d88': 0.0},
         'Joe': {'5dd23a18c7949300087d8d88': 0.8999999761581421}}
    
    for k, v in entity_sentiment_int_int_dict.items():
        if k in entity_sentiment_dictionary.keys():
            entry = entity_sentiment_dictionary[k]
            for update_key, update_val in v.items():
                if update_key in entry:
                    if isinstance(entry[update_key], list):
                        entry[update_key].append(update_val)
                    else:
                        entry[update_key] = [entry[update_key], update_val]
                else:
                    entry[update_key] = update_val
    

    断言测试和实际输出:

    print(f"Result matches desired output: {entity_sentiment_dictionary == out}")
    # Result matches desired output: True
    
    entity_sentiment_dictionary
    
    {'name': {'userid1': [0.0, 0.1]},
     'Aditya': {'userid1': 0.0, 'userid2': 0.3},
     'Glen': {'5dad13fc54aeb500078637e0': -0.10000000149011612},
     'Kenta': {'5dad13fc54aeb500078637e0': 0.0},
     'Keita': {'5dd23a18c7949300087d8d88': 0.0},
     'Ganchan': {'5dd23a18c7949300087d8d88': 0.0},
     'Anna': {'5dd23a18c7949300087d8d88': 0.0},
     'Joe': {'5dd23a18c7949300087d8d88': 0.8999999761581421}}
    

    【讨论】:

    • 嗯。它产生一个空字典。我正在 for 循环之外初始化“条目”。我做错了吗?
    • 不确定 - 我只是使用了您在问题中发布的代码。只需添加所有内容即可获得完整的可重现解决方案。
    • Re entry,如果您的代码中有一个名为 entry 的不同变量可能会导致问题。如果您在干净的环境中运行我的答案中的代码,您可以重现吗?
    • 嘿,我想通了。您之前发布的代码有效。它只是缺少我添加的另一个 else 块
    • 当 key 不存在时,第一个 if 语句的 else 块丢失了。
    【解决方案2】:

    这可以满足您的要求。 可以进一步优化。

    for key in entity_sentiment_int_int_dict.keys():
        if key in entity_sentiment_dictionary.keys():
            if entity_sentiment_dictionary[key].keys() == entity_sentiment_int_int_dict[key].keys():
                temp = []
                temp.append(next(iter(entity_sentiment_dictionary[key].values())))
                temp.append(next(iter(entity_sentiment_int_int_dict[key].values())))
                entity_sentiment_dictionary[key][next(iter(entity_sentiment_dictionary[key].keys()))] = temp
            else:
                entity_sentiment_dictionary[key].update(entity_sentiment_int_int_dict[key])
        else:
            entity_sentiment_dictionary.update(entity_sentiment_int_int_dict[key])
    

    输出

    【讨论】:

    • 绝对没有理由仅仅为了检索第一个值而建立一个列表......只需使用next(iter(<dict>.values())) 代替;效率更高。
    • @JordanBrière 感谢您的建议,我正在寻找这样的东西。更新了答案!
    猜你喜欢
    • 2012-07-15
    • 1970-01-01
    • 2014-09-14
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 2016-10-29
    • 1970-01-01
    相关资源
    最近更新 更多