Home > Back-end >  passing key and value from a list of values to a function in a loop
passing key and value from a list of values to a function in a loop

Time:02-14

I have a dictionary:

my_dict = {
           "port1":["red","chevy"],
           "port2":["orange","ford"],
           "port3":["black","thunderbird"]}

I want to iterate through it and call a function for each combination

my_func(port, color, model):
     do cool stuff

for key, values in my_dict.items():
    for value in values:
      # Here I want to call the function and pass "port1","red","chevy" for the first iteration then "port2","orange","ford" for the 2nd iteration etc..
        my_func("port1", "red", "chevy")

Can't figure out how to do this.

CodePudding user response:

If you know which element in the list you want to pass as each argument to the function then you could do this:

my_func(port, color, model):
 do cool stuff

for key, values in my_dict.items():
    my_func(key, values[0], values[1])
  • Related