简体   繁体   English

遍历字典中的多个键和项目值

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

I'm trying to write a function that takes the keys from a dictionary, and prints them next to every element in that keys corresponding list.我正在尝试编写一个 function,它从字典中获取键,并将它们打印在该键对应列表中的每个元素旁边。 The dictionary has two keys, one with a list of three elements and one with a list of two, how can I use for loops to print the name of the key next to every element in its list?字典有两个键,一个包含三个元素的列表,一个包含两个元素的列表,我如何使用 for 循环在其列表中的每个元素旁边打印键的名称?

edit: I want each key to be printed next to every value of its corresponding list.编辑:我希望每个键都打印在其对应列表的每个值旁边。

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

trying to get the outcome to be试图让结果成为

red apple red shirt red firetruck blue sky blue ocean红苹果 红衬衫 红色救火车 蓝天 蓝色海洋

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

Edit: fixed quotes and casted list items as strings, remove unnecessary format string编辑:将引号和列表项固定为字符串,删除不必要的格式字符串

You can get the value already in the iteration您可以获得迭代中已经存在的值

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

This is my example Index represents the dictionary key.这是我的示例索引代表字典键。 At each loop it takes the key and prints the value first and then the key.在每个循环中,它获取键并首先打印值,然后打印键。

If you want to do it without putting it in a function:如果您想在不将其放入 function 的情况下执行此操作:

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

for index in dict:

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

If you want to do it using a function:如果你想使用 function 来做到这一点:

def fuc_dict(dict):

    for index in dict:

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

OUTPUT OUTPUT

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

I got it, thanks to those who answered.明白了,谢谢回答的人。

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

output: 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