1

this is a sample nested dictionary in JSON format.

{
    "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. example "1001", "1002", "1003" so it gives me following 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...

1 Answer 1

1

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:

{'dict1': {'key': 'value'}, 'dict2': {'1001': {'key1': 'value1', 'key2': 'value2'}, '1002': {'key1': 'value1', 'key2': 'value2'}, '1003': {'key1': 'value1', 'key2': 'value2'}}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.