David542
David542

Reputation: 110502

How to iterate over two different iterable objects

I have the following code:

reader = csv.DictReader(f, delimiter='\x01', lineterminator="\x02")
for line in (reader + my_dict_of_values):
    do_something()

Is there a way that I can iterate over two different types like in the above without calling another function? Otherwise I get: TypeError: unsupported operand type(s) for +: 'instance' and 'dict'.

Upvotes: 1

Views: 108

Answers (2)

dsh
dsh

Reputation: 12234

So you want to iterate over reader and then iterate over my_dict_of_values? sounds like two for-loops in that case.

exactly -- I just have about 100 lines of code in the for loop so want to condense it into one for loop if possible

What you need to do is make the body of your loop a function. Then you can use it in both loops. Change:

for line in reader:
    [100 lines of code]

to:

def do_something(line):
    [100 lines of code]

for line in reader:
    do_something(line)
for key in my_dict_of_values:
    do_something(key)

Upvotes: 0

Cyphase
Cyphase

Reputation: 12022

This should do what you want:

import csv

from itertools import chain

reader = csv.DictReader(f, delimiter='\x01', lineterminator="\x02")
my_dict_of_values = {}  # whatever goes here

for line in chain(reader, my_dict_of_values):
    do_something(line)

Upvotes: 4

Related Questions