1

I built a dictionary list like this

lst = [{'name': nameobj, Classobj1: "string", Classobj2: "string"}, \
{'name': nameobj, Classobj1: "string", Classobj2: "string"}]

and I'm using

for dic in lst:
   for k,v in dic:   # here is the line has probloem! What it happens?
       #process

The error message is like "Classname" object is not iterable.

4 Answers 4

5

Iterating over a dictionary just iterates over the keys, not key-value pairs. So on the line

for k,v in dic:

Python is taking just a key, such as Classobj1, and trying to unpack it to match it to the tuple k,v. Since Classobj1 can't be iterated over, it can't be unpacked to match two items, which is why you get this error.

To iterate over key-value pairs, use items() or iteritems():

for k,v in dic.items():
Sign up to request clarification or add additional context in comments.

Comments

1

You need to use dic.iteritems().

4 Comments

Thanks, but what happened to me~
That is right too. Do you know if there is any differences between our solutions, I mean about speed?Thanks
I only know rudimentary python. I don't think there is and if there is, it is minimal.
The difference between keys and iteritems is what's returned. Keys will return an array of keys where iteritems will return an iterator that yields a tuple(key, value). In most cases it's better to use iterators in loops because they do not make a copy of the data.
0

Try to use

for dic in lst:
    for key in dic.keys():
     /* process dic[key] */

1 Comment

It appears from the code posted that he wants the key and the value, .keys() will only return the keys.
0


for dic in lst:
   for k,v in dic.iteritems():   # just added a call to iteritems
       #process

You get the '<class obj> is not iterable' error because a dict yields its keys when iterating over it, so when you reach say Classobj1 the program expects Classobj1 to be an iterable object that will yield values for k,v.

Comments

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.