根据列表中的属性将python列表排序为列表的字典

时间:2017-02-15 13:57:40

标签: python list dictionary dictionary-comprehension

我正在尝试通过原始列表中对象的属性将python中的对象列表排序为列表字典

我已经在下面完成了,但这感觉就像我应该能够使用词典理解那样做?

for position in totals["positions"]:
        if not hasattr(totals["positions_dict"], position.get_asset_type_display()):
            totals["positions_dict"][position.get_asset_type_display()] = []
        totals["positions_dict"][position.get_asset_type_display()].append(position)

一些自我改进

totals["positions_dict"] = {}
    for position in totals["positions"]:
        key = position.get_asset_type_display()
        if key not in totals["positions_dict"]:
            totals["positions_dict"][key] = []
        totals["positions_dict"][key].append(position)

2 个答案:

答案 0 :(得分:2)

您可以在词典理解中使用itertools.groupbyoperator.methodcaller

from operator import methodcaller
from itertools import groupby

key = methodcaller('get_asset_type_display')
totals["positions_dict"] = {k: list(g) for k, g in groupby(sorted(totals["positions"], key=key), key=key)}

使用@ Jean-FrançoisFabre建议的defaultdict,您只需在一个循环中调用get_asset_type_display()即可完成此操作:

from collections import defaultdict

totals["positions_dict"] = defaultdict(list)
for position in totals["positions"]:
    totals["positions_dict"][position.get_asset_type_display()].append(position)

答案 1 :(得分:0)

没有测试过,因为我没有您的数据。 而且我认为它相当丑陋,但它可能会起作用:

totals ['positions_dict'] = {
    key: [
        position
        for position in totals ['positions']
        if position.get_asset_type_display () == key
    ]
    for key in {
        position.get_asset_type_display ()
        for position in totals ['positions']
    }
}

但我更喜欢一些非常简单的东西,并避免不必要的查询/调用:

positions = totals ['positions']
positions_dict = {}

for position in positions:
    key = position.get_asset_type_display ()
    if key in positions_dict:
        positions_dict [key] .append (position)
    else:
        positions_dict [key] = [position]


totals ['positions_dict'] = positions_dict
positions = totals ['positions']