簡體   English   中英

你能在函數中打印字典嗎

[英]Can you print a dictionary in a function

我在一個函數中有一個輸入,它需要打印字典並實際選擇你想要的數字(根據你的選擇),但它對我不起作用。

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])

它對我來說很好用,我所做的唯一修改是丟棄 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()

輸出:

English
American
French
Spanish

您遍歷字典值(而不是字典大小的索引),並且必須在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 >"))

應該這樣做。 永遠不要在內置變量之后命名變量,你的dict = ....隱藏了內置的dict(..)

輸出:

Gender>  whatever
1: English
2: American
3: French
4: Spanish
Choice >

在 python 中遍歷字典的正確方法是:

for key, item in m_dict.items():

m_dict.items() 將使您可以在 for 循環中使用鍵和項目。 在您的情況下,您可以像這樣使用它:

def print_nationality():
    dict = {
        1: "English",
        2: "American",
        3: "French",
        4: "Spanish"
    }
    for key, item in m_dict.items():
        print(item)

來源: 使用“for”循環迭代字典

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM