简体   繁体   English

什么是通过属性构建字典列表的Pythonic方法?

[英]What Is a Pythonic Way to Build a Dict of Dictionary-Lists by Attribute?

I'm looking for pythonic way to convert list of tuples which looks like this: 我正在寻找pythonic方式来转换元组列表,如下所示:

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

To dict like this: 像这样dict:

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

Now i do this with code like this ( based on this question ): 现在,我使用这样的代码( 基于这个问题 ):

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

Is this a Pythonic way to build dict of lists of objects by attribute? 这是一种Pythonic方法来按属性构建对象列表的dict吗?

I agree with the commentators that here, list comprehension will lack, well, comprehension. 我同意评论员的观点,这里列出的理解力缺乏,理解力很强。

Having said that, here's how it can go: 话虽如此,这是怎么回事:

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}], ...}

The code first sorts by 'type' , then uses itertools.groupby to group by the exact same critera. 代码首先按'type'排序,然后使用itertools.groupby按完全相同的itertools.groupby进行分组。


I stopped understanding this code 15 seconds after I finished writing it :-) 在我写完这篇文章15秒后,我停止了解这段代码:-)

You could do it with a dictionary comprehension, which wouldn't be as illegible or incomprehensible as the comments suggest (IMHO): 你可以用词典理解来做到这一点,这不像评论所暗示的那样难以理解或不可理解(恕我直言):

# 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}]}

Unless I missed something, this should give you the result you're looking for. 除非我错过了什么,否则这应该会给你你正在寻找的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM