Home > Back-end >  for loop with zip in python
for loop with zip in python

Time:06-04

I want to use zip to iterate to existing Lists.

I did that with the code below. Currently the output is just Name --> Name.

How do I use the new creates list or if that's not possible the other lists to print following sentence:

“#NAME is #AGE years old, and they can be called at #NUMBER”. Is it possible to accomplish this in a single loop?

    birth_years = {"Alice": "1990", "Bob": "1990", "Carol": "1995", "Felix":"1995","Max":"1995","Chris":"1998","Lea":"1998","Linn":"1998","Julia":"1998"}
    book = {"Alice": " 1554", "Bob": " 1885", "Carol": " 1006", "Felix":" 1604", "Max":" 1369","Chris":" 1882","Lea":" 1518","Linn":" 1742","Julia":" 1707"} 


   def test(birth_years, books):
      new_list = []
      for birth_year, book in zip(birth_years, books):
        new_list.append(f'{birth_year} -> {book}')
      return new_list

   print(test(birth_years,books))

Thanks!!

BR

CodePudding user response:

zip is not the problem here. The problem is your for loop will simply loop over the keys in the dictionary, rather than the keys and values (see this answer)

The correct way of doing this is:

birth_years = {"Alice": "1990", "Bob": "1990", "Carol": "1995", "Felix":"1995","Max":"1995","Chris":"1998","Lea":"1998","Linn":"1998","Julia":"1998"}
books = {"Alice": " 1554", "Bob": " 1885", "Carol": " 1006", "Felix":" 1604", "Max":" 1369","Chris":" 1882","Lea":" 1518","Linn":" 1742","Julia":" 1707"} 


def test(birth_years, books):
    new_list = []
    for [name, birth_year], [unused, number] in zip(birth_years.items(), books.items()):
        new_list.append(f'{name} is {2022 - int(birth_year)} years old, and they can be called at {number}')
    return new_list

print(test(birth_years,books))
  • Related