Home > OS >  python replace json list values without knowing the keys
python replace json list values without knowing the keys

Time:05-10

I have this code snippet:

data = {
    "links": [
        {"key_name_not_known": "replace_by_first_value_in_list"},
        {"key_name_not_known": "replace_by_second_value_in_list"},
    ]
}

list = ["hello1", "hello2"]

Here I want to replace both values "hello" in data["links"] ["keys"]? without knowing the key value by the two values in the list, in the right order.

A goal output would be:

data = {
    "links": [
        {"key_name_not_known": "hello1"},
        {"key_name_not_known": "hello2"},
    ]
}

How can I do that ?

CodePudding user response:

for index, obj in enumerate(data['links']):
    for key,val in obj.items():
        if len(list) > index:
            data['links'][index][key] = list[index]
  • Related