我有两个python dicts:
payload = {"key1":{"a":"1"},"key2":{"b":"2","c":"3"}}
和
data = {"1":"John","2":"Jacob"}
我希望我的输出为:
{"key1":{"a":"John"},"key2":{"b":"Jacob","c":""}}
我尝试正确打印值的任何方法,但不更新输出字典。
答案 0 :(得分:2)
我知道没有单一的方法,但您可以使用:
for k, v in payload.viewitems():
payload[k] = {}
for kv, vv in v.viewitems():
payload[k][kv] = data.get(vv, "")
如果您再检查payload
它有你所追求的内容:
{'key2': {'c': '', 'b': 'Jacob'}, 'key1': {'a': 'John'}}
答案 1 :(得分:2)
您可以使用dict comprehension
执行此类操作:
payload = {"key1":{"a":"1"},"key2":{"b":"2","c":"3"}}
data = {"1":"John","2":"Jacob"}
final = {k: {i:data[j] if j in data.keys() else "" for i, j in payload[k].items()} for k in payload}
print(final)
输出:
{'key2': {'b': 'Jacob', 'c': ''}, 'key1': {'a': 'John'}}