4
def create_dog_breeds_dictionary(dog_breeds_list, dog_groups_list):
    a_dictionary = dict()
    for x in range(0, len(dog_breeds_list)):
        a_dictionary[dog_groups_list[x]] = list(dog_breeds_list[x].split(","))
    return a_dictionary

def print_key_values_in_order(a_dict):
    for x, y in a_dict.items():
        print(x, y)

This is a question I had for a lab at the university.

I have managed to work out the code for this but I solved it by seeing online that you can use a comma with a for loop and I'm not sure how exactly it works. So the bit I'm confused with is for x, y in a_dict.items(): How exactly does this for loop work?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

1 Answers1

2

That comma is part of tuple unpacking. Specifically, a_dict.items() returns a list of tuples, the first item in each tuple is the key and the second item in each tuple is the value. In that for loop, x is set as the key, and y is set as the value associated with it.

That statement is akin to:

for key in a_dict.keys():
    print(key, a_dict[key])

In this case there's not a particular reason to use one syntax or the other, so go with whatever is more readable for you. In some cases there's no substitute for tuple unpacking.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61