1

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'.

David542
  • 104,438
  • 178
  • 489
  • 842
  • So you want to iterate over `reader` and then iterate over `my_dict_of_values`? sounds like two for-loops in that case. Please don't forget that Dicts are unordered. – Dan Aug 19 '15 at 20:59
  • @Dan -- exactly -- I just have about 100 lines of code in the `for` loop so want to condense it into one for loop if possible. – David542 Aug 19 '15 at 21:00
  • Is `my_dict_of_values` actually a `dict`? Do you want to iterate over the _values_ of the `dict`? – Cyphase Aug 19 '15 at 21:01
  • Oh ok, you can try combining the dicts prior to the for loop, so that you have 1 dict. http://stackoverflow.com/questions/8930915/python-append-dictionary-to-dictionary – Dan Aug 19 '15 at 21:02
  • @David542, wait, are you just trying to add one more dict to the `dicts` in `reader`? – Cyphase Aug 19 '15 at 21:03

2 Answers2

4

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)
Cyphase
  • 11,502
  • 2
  • 31
  • 32
0

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)
Community
  • 1
  • 1
dsh
  • 12,037
  • 3
  • 33
  • 51