2 回答
TA贡献1826条经验 获得超6个赞
这是一个解决方案:
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}}
TA贡献1784条经验 获得超7个赞
这可以满足您的要求。可以进一步优化。
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])
输出
添加回答
举报