python - 如何将列表转换为字典
问题描述
- 我有下面的字典
- 现在 id 是我的钥匙
- 我需要打包值
- 有没有办法像元组拆包一样**val
a = [{ 'id': '123', 'name': 'A', 'type': 'software' },
{ 'id': '102', 'name': 'Adfds', 'type': 'software' },
{ 'id': '222', 'name': 'sxds', 'type': 'software' }]
代码如下
{{key:val} for each in a for key,val in each.items()}
- 我的出处是不正确的字典
预计出局
{ '123': { 'name': 'A', 'type': 'software' },
'102': { 'name': 'Adfds', 'type': 'software' },
'222': { 'name': 'sxds', 'type': 'software' } }
解决方案
字典不能有重复的键。
在您的示例中,您正在向同一个键添加不同的值。在这里你必须做的:
res = {each["id"]: {"name": each["name"], "type": each["type"]} for each in a}