Iterate through a dictionary list and create a new dictionary list

My data is as follows.

[
    {
        "id" : "123",
        "type" : "process",
        "entity" : "abc"
    },
    {
        "id" : "456",
        "type" : "product",
        "entity" : "ab"
    }

]

I am looping, although it looks like this: id and entity

for test in serializer.data:
    qaResultUnique['id'] = test['id']
    qaResultUnique['entity'] = test['entity']
    uniqueList.append(qaResultUnique)

but getting the wrong conclusion as soon as getting the second dictionary both times.

[
        {
            "id" : "456",
            "entity" : "ab"
        },
        {
            "id" : "456",
            "entity" : "ab"
        }

    ]

What am I doing wrong, please help.

+4
source share
4 answers

You are reusing the dictionary object qaResultUnique. Create a new dictionary in a loop every time:

for test in serializer.data:
    qaResultUnique = {}
    qaResultUnique['id'] = test['id']
    qaResultUnique['entity'] = test['entity']
    uniqueList.append(qaResultUnique)

or more briefly expressed:

uniqueList = [{'id': test['id'], 'entity': test['entity']} for test in serializer.data]
+8
source

As @Martijn explained the actual problem , you can really do it with a word understanding like this

keys = {"type"}
print [{k:c_dict[k] for k in c_dict if k not in keys} for c_dict in data]
# [{'id': '123', 'entity': 'abc'}, {'id': '456', 'entity': 'ab'}]

, keys, . , type, entity

keys = {"type", "entity"}
print [{k:c_dict[k] for k in c_dict if k not in keys} for c_dict in data]
# [{'id': '123'}, {'id': '456'}]
+4

.

:

uniqueList.append(qaResultUnique)

:

uniqueList.append(dict(qaResultUnique))
+1

you can always do it like after

for test in serializer.data:
    uniqueList.append({'id':test['id'],'entity':test['entity']})

or in the list comprehension

uniqueList=[{'id':test['id'],'entity':test['entity']} for test in serializer.data]
+1
source

Source: https://habr.com/ru/post/1530626/


All Articles