0

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

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

8 Comments

Hey thanks for your answer. What is unused, number for?
I name it unused because it is unused :). Specifically, both name and unused store the name.
Is it also possible to something like this, that you won't get every name in the output?
1) Yes, you can create a dict which key's are the names, and value are the string
2) you have to create the dict :) so you could use the input
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.