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. 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?
edit: I want each key to be printed next to every value of its corresponding list.
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:
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:
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
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:
red apple
red shirt
red firetruck
blue sky
blue ocean
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.