[英]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 . Python dict 是键值结构 。 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'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.