简体   繁体   English

如何使用变量中的值更新嵌套 Python 字典中的键?

[英]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.

相关问题 如何更改嵌套字典键的 int 值? (Python 3) - How can I change int value of nested dictionary key? (Python 3) Python:如何在嵌套字典中更新键值对的值? - Python: How to update value of key value pair in nested dictionary? 如何直接在 Python 中将字典键作为变量获取(而不是通过从值中搜索)? - How can I get dictionary key as variable directly in Python (not by searching from value)? 如何将值从字典转换为键并使用后续值构建嵌套字典 - How can I transform a value from a dictionary to a key and build a nested dictionary with the subsequent values 如何获取键值对以从嵌套字典创建字典? - How can I get the key value pair to create a dictionary from a nested dictionary? 如何在python中更新字典中的值? - How can I update a value in a dictionary in python? 有人如何通过JSON文件中的嵌套数组在python中多行创建python key:value字典? - How can someone create a python key:value dictionary from a nested array in a JSON file with multiple lines in python? 如何更新嵌套字典中键的值? - How to update value of key in nested dictionary? 如何在Python中切换嵌套字典的值和键? - How can one switch the value and key of a Nested dictionary in Python? 如何更新python中的嵌套字典键 - how to update nested dictionary key in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM