How do I convert a List of Dictionaries that looks something like this:
[{'id':2, 'risk':'a'},
{'id':1, 'risk':'a'},
{'id':32,'risk':'aa'},
{'id':2, 'risk':'aa'},
{'id':7, 'risk':'a'},
{'id':7, 'risk':'b'}]
into a Dictionary of Tuples that will look like this after sorting:
{1:('a', ), 2:('a','aa'), 7:('a','b'), 32:('aa', )}
You can use a defaultdict
to automatically create the tuples, then just iterate over the 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'],)
Which results in:
>>> dict_of_tuples
defaultdict(<type 'tuple'>, {32: ('aa',), 1: ('a',), 2: ('a', 'aa'), 7: ('a', 'b')})
If you then want a sorted dictionary:
>>> from collections import OrderedDict
>>> OrderedDict(sorted(dict_of_tuples.items()))
OrderedDict([(1, ('a',)), (2, ('a', 'aa')), (7, ('a', 'b')), (32, ('aa',))])
The dict.setdefault method makes short work of this kind of problem:
>>> 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']}
You can also use collections.defaultdict to create the same effect, but that doesn't create a regular dictionary and it requires an understanding of factory functions and zero argument constructors.
Generally people forget to use dict.get
method in similar situations. So with basic python functions:
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',)}
Doing it in a longer way. Not as neat as agf's solution, but it works
new_dict = {}
for x in my_dict_list:
m = new_dict.get(x['id'],())
m += (x['risk'],)
new_dict[x['id']] = m
Input
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'}]
Output
>>> new_dict
{32: ('aa',), 1: ('a',), 2: ('a', 'aa'), 7: ('a', 'b')}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.