Archimedes Trajano
Archimedes Trajano

Reputation: 41250

How do I build a dict from key-value pair list?

I am using boto3 to get the EC2 instance tags which has the form

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

I want to convert that to a dict like this

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

Here's my code

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)

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

Seems a bit wordy, I am thinking there should be a one or two line python thing to do that conversion.

Upvotes: 3

Views: 976

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114270

Similar to comprehensions, dict accepts an iterable of pairs, which can be a comprehension as well:

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

OR

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

In python 3.6+, dicts are ordered, so if your dictionary always has 'Value' before 'Key', you can do

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

Of course this latter method is not worth using in a production environment as it is too unreliable.

Upvotes: 2

Ry-
Ry-

Reputation: 224904

Dict comprehensions are a thing:

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

Upvotes: 6

Related Questions