簡體   English   中英

遍歷字典中的多個鍵和項目值

[英]Iterating through multiple keys and item values in a dictionary

我正在嘗試編寫一個 function,它從字典中獲取鍵,並將它們打印在該鍵對應列表中的每個元素旁邊。 字典有兩個鍵,一個包含三個元素的列表,一個包含兩個元素的列表,我如何使用 for 循環在其列表中的每個元素旁邊打印鍵的名稱?

編輯:我希望每個鍵都打印在其對應列表的每個值旁邊。

dictionary = {"red":["apple","shirt","firetruck"], "blue":["sky","ocean"]}

試圖讓結果成為

紅蘋果 紅襯衫 紅色救火車 藍天 藍色海洋

for k in d:
    print(k, " ".join(str(item) for item in d[k]))

編輯:將引號和列表項固定為字符串,刪除不必要的格式字符串

您可以獲得迭代中已經存在的值

for k,v in d.items():
    print("{} {}".format(key, " ".join(v))
for k,v in d.items():
    for vi in v:
        print("{} {}".format(key, vi))

這是我的示例索引代表字典鍵。 在每個循環中,它獲取鍵並首先打印值,然后打印鍵。

如果您想在不將其放入 function 的情況下執行此操作:

dict = {"a": ["1", "2", "3"], "b": ["4", "5"], "c": ["6", "7"]}

for index in dict:

    print("Value: " + str(dict[index]), "Key: " + index)

如果你想使用 function 來做到這一點:

def fuc_dict(dict):

    for index in dict:

        print("Value: " + str(dict[index]), "Key: " + index)

OUTPUT

Value: ['1', '2', '3'] Key: a
Value: ['4', '5'] Key: b
Value: ['6', '7'] Key: c

明白了,謝謝回答的人。

dictionary = {"red":["apple","shirt","firetruck"], "blue":["sky","ocean"]}
for key in dictionary:
    for item in dictionary[key]:
        print("{} {}".format(key, item))

output:

red apple
red shirt
red firetruck
blue sky
blue ocean

暫無
暫無

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

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