2016-02-12 46 views
3

我正在寻找Python的方式转换的元组的列表,它看起来像这样:根据属性建立字典列表字典的Python方法是什么?

res = [{type: 1, name: 'Nick'}, {type: 2, name: 'Helma'}, ...] 

与dict这样的:

{1: [{type: 1, name: 'Nick'}, ...], 2: [{type: 2, name: 'Helma'}, ...]} 

现在我做到这一点,像这样的代码(based on this question):

d = defaultdict(list) 
for v in res: 
    d[v["type"]].append(v) 

这是一种通过属性构建对象列表字典的Python方法吗?

+1

您的解决方案看起来很好 – timgeb

+0

同意。任何使用字典理解的解决方案都可能不太清晰。 – alpha1554

+0

回收我的答案...我同意你的解决方案看起来很好,pythonic –

回答

0

我同意评论员在这里,列表理解将缺乏,以及理解。

说了这么多,下面是它可以去:

import itertools 

a = [{'type': 1, 'name': 'Nick'}, {'type': 2, 'name': 'Helma'}, {'type': 1, 'name': 'Moshe'}] 
by_type = lambda a: a['type'] 
>>> dict([(k, list(g)) for (k, g) in itertools.groupby(sorted(a, key=by_type), key=by_type)]) 
{1: [{'name': 'Nick', 'type': 1}, {'name': 'Moshe', 'type': 1}], ...} 

代码首先通过各种'type',然后由完全相同的性判据使用itertools.groupby到组。


我停下来理解这个代码,我写完这:-)

+0

Tnx,itertools.groupby是我寻找。但是,它看起来很难理解:) – misterion

+0

另一方面,它也是效率低下(因为排序):-)这是一段仅限娱乐的代码 –

0

你可以借助字典理解,它不会被视为难以辨认或者难以理解的意见建议(恕我直言,这样做15秒后):

# A collection of name and type dictionaries 
res = [{'type': 1, 'name': 'Nick'}, 
     {'type': 2, 'name': 'Helma'}, 
     {'type': 3, 'name': 'Steve'}, 
     {'type': 1, 'name': 'Billy'}, 
     {'type': 3, 'name': 'George'}, 
     {'type': 4, 'name': 'Sylvie'}, 
     {'type': 2, 'name': 'Wilfred'}, 
     {'type': 1, 'name': 'Jim'}] 

# Creating a dictionary by type 
res_new = { 
    item['type']: [each for each in res 
        if each['type'] == item['type']] 
    for item in res 
} 

>>>res_new 
{1: [{'name': 'Nick', 'type': 1}, 
    {'name': 'Billy', 'type': 1}, 
    {'name': 'Jim', 'type': 1}], 
2: [{'name': 'Helma', 'type': 2}, 
    {'name': 'Wilfred', 'type': 2}], 
3: [{'name': 'Steve', 'type': 3}, 
    {'name': 'George', 'type': 3}], 
4: [{'name': 'Sylvie', 'type': 4}]} 

除非我错过了什么,这应该会给你你想要的结果。

相关问题