2015-09-23 43 views
-5

我甚至不知道該怎麼稱呼它,因此很難搜索。我有,例如,將一張字典列表映射爲字典列表的字典

people = [ 
    {"age": 22, "first": "John", "last": "Smith"}, 
    {"age": 22, "first": "Jane", "last": "Doe"}, 
    {"age": 41, "first": "Brian", "last": "Johnson"}, 
] 

我想是這樣

什麼是在Python 2要做到這一點最乾淨的方式是什麼?

回答

6

只需循環,並添加到新詞典:

people_by_age = {} 
for person in people: 
    age = person.pop('age') 
    people_by_age.setdefault(age, []).append(person) 

dict.setdefault() method或者返回給定鍵已經存在的價值,或者如果密鑰丟失,使用第二個參數,首先設置鍵。

演示:

>>> people = [ 
...  {"age": 22, "first": "John", "last": "Smith"}, 
...  {"age": 22, "first": "Jane", "last": "Doe"}, 
...  {"age": 41, "first": "Brian", "last": "Johnson"}, 
... ] 
>>> people_by_age = {} 
>>> for person in people: 
...  age = person.pop('age') 
...  people_by_age.setdefault(age, []).append(person) 
... 
>>> people_by_age 
{41: [{'last': 'Johnson', 'first': 'Brian'}], 22: [{'last': 'Smith', 'first': 'John'}, {'last': 'Doe', 'first': 'Jane'}]} 
>>> from pprint import pprint 
>>> pprint(people_by_age) 
{22: [{'first': 'John', 'last': 'Smith'}, {'first': 'Jane', 'last': 'Doe'}], 
41: [{'first': 'Brian', 'last': 'Johnson'}]} 
+0

謝謝!這完美地回答了我的問題。 – user280993

2

defaultdict使用方法和dictonary.pop method

代碼:

from collections import defaultdict 

people = [ 
    {"age": 22, "first": "John", "last": "Smith"}, 
    {"age": 22, "first": "Jane", "last": "Doe"}, 
    {"age": 41, "first": "Brian", "last": "Johnson"}, 
] 

d = defaultdict(int) 

people_dic = defaultdict(list) 
for element in people: 
    age = element.pop('age') 
    people_dic[age].append(element) 

print(people_dic) 

輸出:

defaultdict(<type 'list'>, {41: [{'last': 'Johnson', 'first': 'Brian'}], 22: [{'last': 'Smith', 'first': 'John'}, {'last': 'Doe', 'first': 'Jane'}]})