从字典列表中创建特定键和值的字典



我有一个字典列表,看起来像这样:

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'}

相关内容

  • 没有找到相关文章

最新更新