Chained Iteration With chain
Chained Iteration With chain
itertools
also provides chain(*iterables)
, which gets some iterables
as arguments and makes an iterator that yields elements from the first iterable until it’s exhausted, then iterates over the next iterable and so on, until all of them are exhausted.
This allows you to iterate through multiple dictionaries in a chain, like to what you did with collections.ChainMap
:
>>>
>>> from itertools import chain >>> fruit_prices = {'apple': 0.40, 'orange': 0.35, 'banana': 0.25} >>> vegetable_prices = {'pepper': 0.20, 'onion': 0.55, 'tomato': 0.42} >>> for item in chain(fruit_prices.items(), vegetable_prices.items()): ... print(item) ... ('apple', 0.4) ('orange', 0.35) ('banana', 0.25) ('pepper', 0.2) ('onion', 0.55) ('tomato', 0.42)
Comments (0)