我有一个字典列表,看起来像这样:
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'}
]
我想创建一个包含所有id
值和name
值的字典,因此输出将如下所示:
{'Team1': 'Team One', 'Team2': 'Team Two', 'Team3': 'Team Three'}
实现这一点的最佳python方法是什么?
感谢Usingoperator.itemgetter
:
from operator import itemgetter
out = dict(map(itemgetter('id', 'name'), dic))
输出:{'Team1': 'Team One', 'Team2': 'Team Two', 'Team3': 'Team Three'}
输入:使用
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'}]
您可以使用字典推导:
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'}
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'}