Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through list of dictionary and create new list of dictionary

My data is as follows.

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

]

I am looping though it as follows to get id and entity

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

but getting wrong output as only getting 2nd dictionary both times .

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

    ]

What I am doing wrong , please help.

like image 556
Pawan Avatar asked Dec 08 '22 09:12

Pawan


2 Answers

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

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

or more succinctly expressed:

uniqueList = [{'id': test['id'], 'entity': test['entity']} for test in serializer.data]
like image 137
Martijn Pieters Avatar answered Dec 11 '22 10:12

Martijn Pieters


As @Martijn explained the actual problem, you can actually do this with dictionary comprehension 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'}]

You can use this method to skip any number of keys, without having to change the dictionary comprehension part. For example, if you have to skip both type and 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'}]
like image 21
thefourtheye Avatar answered Dec 11 '22 09:12

thefourtheye