'Create Dictionary of Specific Keys and Values from a Lst of Dictionaries
I have a list of dictionaries which looks like this:
dic = [
{'id': 'Team1', 'name': 'Team One', 'description': 'This is team 1', 'type': 'team'},
{'id': 'Team2', 'name': 'Team Two', 'description': 'This is team 2', 'type': 'team'},
{'id': 'Team3', 'name': 'Team Three', 'description': 'This is team 3', 'type': 'team'}
]
I want to create a dictionary of all the id
values and name
values so the output will look like this:
{'Team1': 'Team One', 'Team2': 'Team Two', 'Team3': 'Team Three'}
What is the best pythonic way of achieving this?
Thanks
Solution 1:[1]
Using operator.itemgetter
:
from operator import itemgetter
out = dict(map(itemgetter('id', 'name'), dic))
output: {'Team1': 'Team One', 'Team2': 'Team Two', 'Team3': 'Team Three'}
used input:
dic = [{'id': 'Team1', 'name': 'Team One', 'description': 'This is team 1', 'type': 'team'},
{'id': 'Team2', 'name': 'Team Two', 'description': 'This is team 2', 'type': 'team'},
{'id': 'Team3', 'name': 'Team Three', 'description': 'This is team 3', 'type': 'team'}]
Solution 2:[2]
You can use dict comprehension:
dcts = [ {'id': 'Team1', 'name': 'Team One', 'description': 'This is team 1', 'type': 'team'}, {'id': 'Team2', 'name': 'Team Two', 'description': 'This is team 2', 'type': 'team'}, {'id': 'Team3', 'name': 'Team Three', 'description': 'This is team 3', 'type': 'team'} ]
output = {dct['id']: dct['name'] for dct in dcts}
print(output) # {'Team1': 'Team One', 'Team2': 'Team Two', 'Team3': 'Team Three'}
Solution 3:[3]
dictt = [ {'id': 'Team1', 'name': 'Team One', 'description': 'This is team 1', 'type': 'team'}, {'id': 'Team2', 'name': 'Team Two', 'description': 'This is team 2', 'type': 'team'}, {'id': 'Team3', 'name': 'Team Three', 'description': 'This is team 3', 'type': 'team'} ]
new={}
for a in dictt:
new[a['id']]=a['name']
print (new)
#{'Team1': 'Team One', 'Team2': 'Team Two', 'Team3': 'Team Three'}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mozway |
Solution 2 | Kelly Bundy |
Solution 3 |