2

I have a dictionary with each key containing a list as a value. And I'm trying to go over all the items in the lists, and let's say I'm trying to print all the items as I go through, I wrote:

for item in aDict: 
    for item2 in aDict[item]: 
        print item2

This prints out the items in the list for the first value, then it gives me an error saying "iteration over non-sequence". Why is this and how should I do this?

Thanks in advance.

Dennis
  • 3,506
  • 5
  • 34
  • 42
  • Side note (doesn't solve your problem): Use `iteritems()` instead: `for (i, lst) in aDict.iteritems(): for item2 in lst: ...` – Marcelo Cantos Dec 05 '11 at 21:16
  • 1
    I suspect @StevenRumbalski and @Ben hit the nail on the head for this one. You might try inserting a print statement between the two `for`-loops as a way to figure out what exactly is in there. – David H. Clements Dec 05 '11 at 21:18

4 Answers4

7

One of your dictionary values is not a list!

Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
  • Oh shoot I didn't see this one key that had an integer value.. I should've been more careful... :( Thanks anyways! – Dennis Dec 05 '11 at 21:17
5

I'm assuming one of the items in aDict is not a sequence, string, list, tuple etc:

>>> aDict = { 'a' : [1, 2, 3,], 'b' : [4, 5, 6,], 'c' : [7, 8, 9,] }
>>> for item in aDict:
...     for item2 in aDict[item]:
...         print item2
...
1
2
3
7
8
9
4
5
6
>>>
Ben
  • 51,770
  • 36
  • 127
  • 149
  • Oh shoot I didn't see this one key that had an integer value.. I should've been more careful... :( Thanks anyways! – Dennis Dec 05 '11 at 21:17
0

When you do this:

for item in aDict: 
    for item2 in aDict[item]: 
        print item2

Your saying, for each item in the dictionary, loop through the item index in the dictionary, which doesn't make any sense.

What you really want to do is for each item, loop through that specific item, like:

for item in aDict: 
    for item2 in item: 
        print item2

or using better terms:

for dictIndex in aDict: 
        for item in dictIndex: 
            print item
slandau
  • 23,528
  • 42
  • 122
  • 184
  • No, that's not it. `for item in aDict` iterates over *keys*. So he really does need to do `aDict[item]`. (Or just do `for item in aDict.values():`) – Steven Rumbalski Dec 05 '11 at 21:20
0

aDict[item] implies that you want the values of the dict, not the keys? In which case .itervalues() or .iteritems() should be more natural than the default iteration (over keys only).

for key, value in aDict.iteritems():
    for subvalue in value:
        pass

The error points to (at least one of) your values is not iterable.

ephemient
  • 198,619
  • 38
  • 280
  • 391