python - 什么是按属性构建字典列表的 Pythonic 方法?

标签 python list dictionary list-comprehension

我正在寻找 pythonic 方法来转换元组列表,如下所示:

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

像这样听写:

 {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)

这是按属性构建对象列表字典的 Pythonic 方式吗?

最佳答案

我同意评论员的观点,在这里,列表理解将缺乏理解。

话虽如此,这是它的发展方式:

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按完全相同的条件分组。


我在写完这段代码 15 秒后就不再理解它了:-)

关于python - 什么是按属性构建字典列表的 Pythonic 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35360489/

相关文章:

python-2.7 - 如何在 python 列表中追加行?

python - 遍历 Python 中的整数列表和列表

javascript - 如何将对象的属性和值映射到表?

python - 如何使用pyAudio获得左输出

Python/Pandas - 更新一组记录的数据

python - pycrypto 需要 Visual Studio 吗?

Python与无限集成

python-3.x - 我在使用 *mul* 运算符乘以变量时遇到问题

Python 脚本从列表中删除唯一元素并按正确顺序打印重复元素的列表

ios - 使枚举数组符合 Hashable 以用作字典键