[英]Can you print a dictionary in a function
I have an input in a function, where it requires to print a dictionary and actually choose the number you want (based on your choice) however its not working for me.我在一个函数中有一个输入,它需要打印字典并实际选择你想要的数字(根据你的选择),但它对我不起作用。
def add_item():
item = str(input("Gender> "))
types = int(input(print_nationality(), "Choice >"))
...
def print_nationality():
dict = {
1: "English",
2: "American",
3: "French",
4: "Spanish"
}
for i in range(len(dict)):
print(dict[i])
it works fine for me, the only modification I made is to discard 0 and start from 1 (and for good practice renamed the variable to name that is not type, well not recommended):它对我来说很好用,我所做的唯一修改是丢弃 0 并从 1 开始(为了良好的实践,将变量重命名为非类型的名称,不推荐):
def print_nationality():
m_dict = {
1: "English",
2: "American",
3: "French",
4: "Spanish"
}
for i in range(1,len(m_dict)+1):
print(m_dict [i])
print_nationality()
output:输出:
English
American
French
Spanish
You loop over the dictionary values (not over the index of the size of dictionary) and you have to call print_nationality()
before and not inside the input(..)
command:您遍历字典值(而不是字典大小的索引),并且必须在input(..)
命令之前而不是在内部调用print_nationality()
:
def print_nationality():
menu = {
1: "English",
2: "American",
3: "French",
4: "Spanish"
}
# directly iterate the keys of the dict
for i in menu:
print(f"{i}: {menu[i]}")
def add_item():
item = str(input("Gender> "))
# print first, then ask for input
print_nationality()
types = int(input("Choice >"))
should do it.应该这样做。 Never name variables after built ins, your dict = ....
hides the dict(..)
built in.永远不要在内置变量之后命名变量,你的dict = ....
隐藏了内置的dict(..)
。
Output:输出:
Gender> whatever
1: English
2: American
3: French
4: Spanish
Choice >
The correct way of iterating through a dictionary in python would be:在 python 中遍历字典的正确方法是:
for key, item in m_dict.items():
The m_dict.items() will give you the possibility to use the key and the item in the for loop. m_dict.items() 将使您可以在 for 循环中使用键和项目。 In your case you could use it like this:在您的情况下,您可以像这样使用它:
def print_nationality():
dict = {
1: "English",
2: "American",
3: "French",
4: "Spanish"
}
for key, item in m_dict.items():
print(item)
Source: Iterating over dictionaries using 'for' loops来源: 使用“for”循环迭代字典
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.