简体   繁体   中英

convert a list of dicts to a dict of dicts python3

I have a list of dicts which looks like this

a = [{'name': 'analyst21', 'id': 1, 'data': 'the process data3'}, {'name': 'analyst2', 'id': 2, 'data': 'process data2'}, {'name': 'analyst3', 'id': 3, 'data': 'process data3'}]

i want to convert it to dict of dicts

Required output:

a = {{'name': 'analyst21', 'id': 1, 'data': 'the process data3'}, {'name': 'analyst2', 'id': 2, 'data': 'process data2'}, {'name': 'analyst3', 'id': 3, 'data': 'process data3'}}

I Know that dict needs key-value pairs. Is any other way to make it possible. is my question is wrong. Got some negative votes. I just want the list data to be enclosed inside this {} . I use these results for further processing.

Python dict is key-value structure . Your required output is not a dict - dict must have both keys and corresponding values (or be empty). If you want to convert a list of dicts to a dict of dicts, you should chose a some kind of hashable key (note that dict itself is not hashable so you can't use ordinary dicts as keys!) and use them as dict keys. Here is the example how you can to do it:

a = [{'name': 'analyst21', 'id': 1, 'data': 'the process data3'},
     {'name': 'analyst2', 'id': 2, 'data': 'process data2'},
     {'name': 'analyst3', 'id': 3, 'data': 'process data3'}]

b = {d['name']: d for d in a}
b

will return you a dict:

{'analyst2': {'data': 'process data2', 'id': 2, 'name': 'analyst2'},
 'analyst21': {'data': 'the process data3', 'id': 1, 'name': 'analyst21'},
 'analyst3': {'data': 'process data3', 'id': 3, 'name': 'analyst3'}}

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.

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