2014-04-27 71 views
0

嗨複製我有類型的字典的數組,看起來像這樣:提取從字典中的陣列

books = [ 
     {'Serial Number': '3333', 'size':'500', 'Book':'The Hobbit'}, 
     {'Serial Number': '2222', 'size':'100', 'Book':'Lord of the Rings'}, 
     {'Serial Number': '1111', 'size':'200', 'Book':'39 Steps'}, 
     {'Serial Number': '3333', 'size':'600', 'Book':'100 Dalmations'}, 
     {'Serial Number': '2222', 'size':'800', 'Book':'Woman in Black'}, 
     {'Serial Number': '6666', 'size':'1000', 'Book':'The Hunt for Red October'}, 
     ] 

我需要創建類型的字典單獨的數組,看起來像這樣基於重複的序列號:

duplicates = [ 
    '3333', [{'Book':'The Hobbit'}, {'Book':'100 Dalmations'}], 
    '2222', [{'Book':'Lord of the Rings'}, {'Book':'Woman in Black'}] 
] 

有沒有一種簡單的方法來使用內置函數來做到這一點,如果不是最好的方式來實現這一目標?

+0

如果有大於1次的重複嗎? – thefourtheye

+0

好問題,我修改了我的問題,以考慮到這一點! – user1513388

+0

你的編輯不是一個有效的Python數據結構。 – roippi

回答

0

最Python的方式我能想到的:

from collections import defaultdict 
res = defaultdict(list) 

for d in books: 
    res[d.pop('Serial Number')].append(d) 

print({k: v for k, v in res.items() if len(v) > 1}) 

輸出:

{'2222': [{'Book': 'Lord of the Rings', 'size': '100'}, 
      {'Book': 'Woman in Black', 'size': '800'}], 
'3333': [{'Book': 'The Hobbit', 'size': '500'}, 
      {'Book': '100 Dalmations', 'size': '600'}]} 
+0

這似乎很好。但是,我現在如何才能獲得這個新結構中每本書的「大小」? – user1513388

+0

@ user1513388例如對於霍比特人:'hobbit = [x for x in duplicates ['2222'] if x ['Book'] =='Hobbit'] [0]'。現在你可以像這樣得到尺寸:'hobbit ['size']' – vaultah