[英]Python: How can loop over two lists one for key and one for value and place that into a new empty dictionary?
Here is the data I have I want to loop over the two lists the symbol list as the key and symbol_name as the value how do I do it with using the loop这是我想要在两个列表中循环的数据,符号列表作为键,符号名称作为值我如何使用循环来做到这一点
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)
What i want to be printed is:我想要打印的是:
calculator_dict = {
"+": "add",
"-": "subtract",
"*": "multiply",
"/": "divide",
}
Use the zip
and dict
functions:使用
zip
和dict
函数:
>>> symbols = ["+", "-", "*", "/"]
>>> symbol_name = ["add", "subtract", "multiply", "divide"]
>>> dict(zip(symbols, symbol_name))
{'+': 'add', '-': 'subtract', '*': 'multiply', '/': 'divide'}
You can also use a dict comprehension over the zipped lists:您还可以对压缩列表使用 dict 理解:
>>> symbols = ["+", "-", "*", "/"]
>>> symbol_name = ["add", "subtract", "multiply", "divide"]
>>> calculator_dict = { s:n for s,n in zip(symbols, symbol_name) }
{'+': 'add', '-': 'subtract', '*': 'multiply', '/': 'divide'}
This is useful if you need more fine-grained control.如果您需要更细粒度的控制,这很有用。
For example, uppercase the values:例如,将值大写:
>>> { s:n.capitalize() for s,n in zip(symbols, symbol_name) }
{'+': 'ADD', '-': 'SUBTRACT', '*': 'MULTIPLY', '/': 'DIVIDE'}
Or filter values by length:或按长度过滤值:
>>> { s:n for s,n in zip(symbols, symbol_name) if len(n) < 5 }
{'+': 'add'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.