17 - 将两个列表或元组合并成一个字典

如何将两个列表或元组合并成一个字典,形式如下

a = [‘a’, ‘b’] # 列表1

b = [1, 2] # 列表2

合并后:{‘a’: 1, ‘b’: 2}

# 这种合并方式主要用于将数据表的字段与记录值合并成一个字典,
# 一般会返回给客户端以便进行其他处理
a = ['a', 'b']
b = [1, 2]

print(dict(zip(a, b)))

fields = ('id', 'name', 'age')
records = [['01', 'Bill', '20'], ['02', 'Mike', '30']]

result = []
for record in records:
    result.append(dict(zip(fields, record)))
print(result)
{'a': 1, 'b': 2}
[{'id': '01', 'name': 'Bill', 'age': '20'}, {'id': '02', 'name': 'Mike', 'age': '30'}]

18 - 详细描述列表与元组的差异

发布了110 篇原创文章 · 获赞 104 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_29339467/article/details/104319380