一、字典生成式
二、代码示例
items = ["Fruits", "Books", "Others"] # 列表
prices = [96, 78, 85] # 列表
d = {item: price for item, price in zip(items, prices)}
print(d, type(d))
d = {item.upper(): price for item, price in zip(items, prices)}
print(d, type(d))
items = ["Fruits", "Books", "Others"] # zip()打包以元素个数较少的为准
prices = [96, 78, 85, 100, 120]
d = {item.upper(): price for item, price in zip(items, prices)}
print(d, type(d))
items = ["Fruits", "Books", "Others", "jobs"]
prices = [96, 78, 85] # zip()打包以元素个数较少的为准
d = {item.upper(): price for item, price in zip(items, prices)}
print(d, type(d))
运行结果:
D:\Environment\Python\Python311\python.exe D:\Environment\PythonWorks\learnpython\马士兵Python\第7章_夫妻站\P66_65.字典生成式.py
{'Fruits': 96, 'Books': 78, 'Others': 85} <class 'dict'>
{'FRUITS': 96, 'BOOKS': 78, 'OTHERS': 85} <class 'dict'>
{'FRUITS': 96, 'BOOKS': 78, 'OTHERS': 85} <class 'dict'>
{'FRUITS': 96, 'BOOKS': 78, 'OTHERS': 85} <class 'dict'>
Process finished with exit code 0