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
keys 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
CodePudding user response:
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'}]
CodePudding user response:
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'}
CodePudding user response:
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'}