[英]How can i update key in nested Python dictionary with a value from a variable?
this is a sample nested dictionary in JSON format.这是JSON格式的示例嵌套字典。
{
"dict1": {
"key": "value",
},
"dict2": {
"dict_id": {
"key1": "value1",
"key2": "value2"
}
}
}
I would like to replace " dict_id " with a string derived from a variable which generates IDs in Numbers.我想用一个从在数字中生成 ID 的变量派生的字符串替换“ dict_id ”。 example "1001", "1002", "1003" so it gives me following output.
例如“1001”、“1002”、“1003”,所以它让我关注 output。
{
"dict1": {
"key": "value",
},
"dict2": {
"1001": {
"key1": "value1",
"key2": "value2",
},
"1002": {
"key1": "value1",
"key2": "value2",
},
"1003": {
"key1": "value1",
"key2": "value2",
}
}
}
how can i get the above results?, any help will be appreciated.我怎样才能得到上述结果?,任何帮助将不胜感激。 thanks...
谢谢...
A simple dictionary comprehension should work here to restructure the dictionary:一个简单的字典理解应该在这里重新构建字典:
d = {
"dict1": {
"key": "value",
},
"dict2": {
"dict_id": {
"key1": "value1",
"key2": "value2"
}
}
}
ids = ["1001", "1002", "1003"]
result = {"dict1": d["dict1"], "dict2": {i: d["dict2"]["dict_id"] for i in ids}}
print(result)
Output: Output:
{'dict1': {'key': 'value'}, 'dict2': {'1001': {'key1': 'value1', 'key2': 'value2'}, '1002': {'key1': 'value1', 'key2': 'value2'}, '1003': {'key1': 'value1', 'key2': 'value2'}}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.