2014-03-07 166 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]