本文讨论如何将两个列表转换成一个字典,要求两个列表满足以下条件
输入:
name_lst = ['python', 'java', 'php']
value_lst = [90, 99, 95]
输出:
{
'python': 90,
'java': 99,
'php': 95
}
name_lst = ['python', 'java', 'php']
value_lst = [90, 99, 95]
dic = {}
for index, key in enumerate(name_lst):
dic[key] = value_lst[index]
print(dic)
遍历大法好,用了忘不了,不管是什么问题,只要能遍历,就没有解决不了的
name_lst = ['python', 'java', 'php']
value_lst = [90, 99, 95]
dic = dict(zip(name_lst, value_lst))
print(dic)
dict究竟是如何起作用的呢,可以参考下面的代码
print(dict([('python', 90), ('java', 99)]))
列表里有连个元组,dict函数会将这个两个元组转换成key-value对,最终的结果是
{'python': 90, 'java': 99}
name_lst = ['python', 'java', 'php']
value_lst = [90, 99, 95]
dic = {key: value for key, value in zip(name_lst, value_lst)}
print(dic)
QQ交流群: 211426309