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.
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]
                        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'}]
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With