如何从键值对列表构建dict?

2024-05-16 22:19:18 发布

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

我使用boto3来获取EC2实例标记,它的形式是

[{u'Value': 'swarm manager 0', u'Key': 'Name'}, {u'Value': 'manager', u'Key': 'Role'}]

我想把它转换成这样的口述

{'Name': 'swarm manager 0', 'Role': 'manager'}

这是我的密码

tags = [{u'Value': 'swarm manager 0', u'Key': 'Name'}, {u'Value': 'manager', u'Key': 'Role'}]
tag_dict = dict()
for tag in tags:
  tag_dict[tag['Key']]=tag['Value']
print(tag_dict)

https://repl.it/@trajano/GargantuanStickyNasm

似乎有点罗嗦,我想应该有一个一行或两行python的东西来完成转换


Tags: 实例keyname标记valuetagtagsmanager
2条回答

Dict comprehensions是一件事:

tag_dict = {tag['Key']: tag['Value'] for tag in tags}

与理解类似,dict接受成对的iterable,也可以是理解:

from operator import itemgetter
dict(map(itemgetter('Key', 'Value'), tags))

dict(itemgetter('Key', 'Value')(x) for x in tags)

在Python3.6+中,dict是按顺序排列的,因此如果您的字典在'Key'之前总是有'Value',那么您可以这样做

dict(x.values()[::-1] for x in tags)

当然,后一种方法不值得在生产环境中使用,因为它太不可靠了

相关问题 更多 >