Python:如何循环两个列表,一个用于键,一个用于值,并将其放入新的空字典中?
这是我想要循环的两个列表的数据,符号列表作为键,符号名称作为值 我如何使用循环来实现它Python:如何循环两个列表,一个用于键,一个用于值,并将其放入新的空字典中?,python,list,loops,dictionary,for-loop,Python,List,Loops,Dictionary,For Loop,这是我想要循环的两个列表的数据,符号列表作为键,符号名称作为值 我如何使用循环来实现它 calculator_dict = {} # the new dictionary i want to put both the list into symbols = ["+", "-", "*", "/"] symbol_name = ["add", "subtract", &q
calculator_dict = {} # the new dictionary i want to put both the list into
symbols = ["+", "-", "*", "/"]
symbol_name = ["add", "subtract", "multiply", "divide"]
for symbol in symbols:
for name in symbol_name:
calculator_dict[symbol] = name
print(calculator_dict)
我想要打印的是:
calculator_dict = {
"+": "add",
"-": "subtract",
"*": "multiply",
"/": "divide",
}
使用zip和dict功能:
>>> symbols = ["+", "-", "*", "/"]
>>> symbol_name = ["add", "subtract", "multiply", "divide"]
>>> dict(zip(symbols, symbol_name))
{'+': 'add', '-': 'subtract', '*': 'multiply', '/': 'divide'}
您还可以在压缩列表上使用dict理解: >>>符号=[+,-,*,/] >>>symbol_name=[加、减、乘、除] >>>计算器_dict={s:n表示s,n表示zipsymbols,symbol_name} {'+':'加','-':'减','*':'乘','/':'除'} 如果您需要更细粒度的控制,这非常有用 例如,大写字母表示值: >>>{s:n.s的大写字母,n在zipsymbols中,symbol_name} {'+':'加','-':'减','*':'乘','/':'除'} 或按长度筛选值: >>>{s:n表示s,n表示zipsymbols,如果lenn<5,则表示符号_name} {'+':'add'}
这回答了你的问题吗?