Home > Back-end >  merge common keys and its value individually in python dictionary
merge common keys and its value individually in python dictionary

Time:01-12

i have seen lot of answers related to my question but none of them solved my question

here is the input question:

data = { "data": [{ key1:word},{ key1:hello},{key2:hey},{key2:hi}]}  

expected output:

{key1:word, key2:hey}, {key1:hello, key2:hi}

here is what i have tried:

 for key,items in data.items():
    if key == "key1":
        do something
    if key == "key2":
        do something

but the above cannot be used for 1000 key pair values, so the code should be dynamic. in future key4, key5, key6....etc can be added so each key items i cant define in condition.

CodePudding user response:

Do you just want to do this?

for dic in data["data"]:
    key = dic.keys()[0]
    value = dic.values()[0]
    if key == "key1":
        do something
    if key == "key2":
        do something

CodePudding user response:

Interesting request..... I think this might be what you needed?

data = [{ "key1":"value1"},{ "key1":"hello"},{"key2":"value2"},{"key2":"value3"}] 

odd_entries = data[::2]  # Iterate by twos, starting at 0
even_entries = data[1::2]  # Iterate by twos, starting at 1

print(list(zip(odd_entries, even_entries)))
  •  Tags:  
  • Related