2014-03-07 168 views
4

我的数据如下。遍历字典列表并创建新的字典列表

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

] 

我循环虽然如下得到ID和实体

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

,但得到错误的输出只获得第2字典两次。

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

    ] 

我在做什么错,请帮助。

+2

新列表中的两个元素都是相同的字典 – M4rtini

回答

8

您正在重新使用qaResultUnique字典对象。创建字典在每次循环:

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

或更简洁地表示:

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

由于@Martijn explained the actual problem,你其实可以像这样

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,而不必更改字典comprehen sion部分。例如,如果你要跳过这两者typeentity

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'}] 
+0

字典理解仅在Python 2.7+中可用。 –

+0

@MattBriançon你是对的:) – thefourtheye

1

就修改这个样子。

前:

uniqueList.append(qaResultUnique) 

后:

uniqueList.append(dict(qaResultUnique)) 
1

你总是可以做到像以下

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

或列表理解

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