如何将列表转换为字典

2024-09-30 20:19:36 发布

您现在位置:Python中文网/ 问答频道 /正文

  • 我在下面写了一篇短文
  • 现在身份证是我的钥匙
  • 我需要打包这些值
  • 有没有办法像元组一样解包
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' } }

Tags: keynameinidfortypesoftwareval
3条回答

您可以尝试以下方法:

a=[{ 'id': '123', 'name': 'A', 'type': 'software' }, { 'id': '102', 'name': 'Adfds', 'type': 'software' }, { 'id': '222', 'name': 'sxds', 'type': 'software' }]

b = {}

for item in a:
    b[item.pop("id")] = item

b

输出:

enter image description here

您可以这样做:

{e['id']: dict(i for i in e.items() if i[0] != 'id') for e in a}

字典不能有重复的键

在您的示例中,您正在向同一个键添加不同的值。以下是您必须做的:

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

相关问题 更多 >