首页 > 解决方案 > 如何将列表转换为字典

问题描述

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' } }

标签: python

解决方案


字典不能有重复的键。

在您的示例中,您正在向同一个键添加不同的值。在这里你必须做的:

res = {each["id"]: {"name": each["name"], "type": each["type"]} for each in a}

推荐阅读