3

如何转换看起来像这样的字典列表:

[{'id':2, 'risk':'a'}, 
 {'id':1, 'risk':'a'}, 
 {'id':32,'risk':'aa'},
 {'id':2, 'risk':'aa'}, 
 {'id':7, 'risk':'a'}, 
 {'id':7, 'risk':'b'}]

进入一个元组字典,排序后看起来像这样:

{1:('a', ), 2:('a','aa'), 7:('a','b'), 32:('aa', )}
4

4 回答 4

4

您可以使用 adefaultdict自动创建元组,然后只需遍历list_of_dicts

list_of_dicts = [{'id':2, 'risk':'a'}, 
 {'id':1, 'risk':'a'}, 
 {'id':32,'risk':'aa'},
 {'id':2, 'risk':'aa'}, 
 {'id':7, 'risk':'a'}, 
 {'id':7, 'risk':'b'}]

from collections import defaultdict

dict_of_tuples = defaultdict(tuple)

for dct in list_of_dicts:
    dict_of_tuples[dct['id']] += (dct['risk'],)

结果是:

>>> dict_of_tuples
defaultdict(<type 'tuple'>, {32: ('aa',), 1: ('a',), 2: ('a', 'aa'), 7: ('a', 'b')})

如果你想要一个排序的字典:

>>> from collections import OrderedDict
>>> OrderedDict(sorted(dict_of_tuples.items()))
OrderedDict([(1, ('a',)), (2, ('a', 'aa')), (7, ('a', 'b')), (32, ('aa',))])
于 2013-04-10T05:06:13.513 回答
3

dict.setdefault方法可以轻松解决此类问题:

>>> lod = [{'id':2, 'risk':'a'}, 
           {'id':1, 'risk':'a'}, 
           {'id':32,'risk':'aa'},
           {'id':2, 'risk':'aa'}, 
           {'id':7, 'risk':'a'}, 
           {'id':7, 'risk':'b'}]
>>> dot = {}
>>> for d in lod:
        idnum, risk = d['id'], d['risk']
        dot.setdefault(idnum, []).append(risk)

>>> dot
{32: ['aa'], 1: ['a'], 2: ['a', 'aa'], 7: ['a', 'b']}

您也可以使用collections.defaultdict创建相同的效果,但这不会创建常规字典,并且需要了解工厂函数和零参数构造函数。

于 2013-04-10T05:22:06.157 回答
2

dict.get通常人们在类似的情况下忘记使用方法。所以使用基本的python函数:

list_of_dicts = [{'id':2, 'risk':'a'}, 
    {'id':1, 'risk':'a'}, 
    {'id':32,'risk':'aa'},
    {'id':2, 'risk':'aa'}, 
    {'id':7, 'risk':'a'}, 
    {'id':7, 'risk':'b'}]

final_dict = {}

for item in list_of_dicts:
    final_dict[item['id']] = final_dict.get(item['id'], tuple()) + (item['risk'],)


>> {1: ('a',), 2: ('a', 'aa'), 7: ('a', 'b'), 32: ('aa',)}
于 2013-04-10T08:19:59.737 回答
0

以更长的方式进行。不像 agf 的解决方案那样简洁,但它有效

new_dict = {}
for x in my_dict_list: 
    m = new_dict.get(x['id'],())
    m += (x['risk'],)
    new_dict[x['id']] = m

输入

my_dict_list = [{'id':2, 'risk':'a'}, 
                {'id':1, 'risk':'a'}, 
                {'id':32,'risk':'aa'},
                {'id':2, 'risk':'aa'}, 
                {'id':7, 'risk':'a'}, 
                {'id':7, 'risk':'b'}]

输出

>>> new_dict
{32: ('aa',), 1: ('a',), 2: ('a', 'aa'), 7: ('a', 'b')}
于 2013-04-10T05:12:54.737 回答