将两个列表映射到Python中的字典中 [英] Map two lists into a dictionary in Python

查看:600
本文介绍了将两个列表映射到Python中的字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,你有:

keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')

什么是最简单的生产方式以下字典?

What is the simplest way to produce the following dictionary ?

a_dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}

此代码有效,但我并不为此感到自豪:

This code works, but I'm not really proud of it :

a_dict = {}
junk = map(lambda k, v: a_dict.update({k: v}), keys, values)


推荐答案

像这样:

>>> keys = ['a', 'b', 'c']
>>> values = [1, 2, 3]
>>> dictionary = dict(zip(keys, values))
>>> print(dictionary)
{'a': 1, 'b': 2, 'c': 3}

Voila :-)成对的dict构造函数和zip函数非常有用: https://docs.python.org/3/library/functions.html#func-dict

Voila :-) The pairwise dict constructor and zip function are awesomely useful: https://docs.python.org/3/library/functions.html#func-dict

这篇关于将两个列表映射到Python中的字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆