Reputation: 37876
i know, this might be easy, but i am stuck whatsoever.. this is the data
{ u'job_27301': [{u'auto_approve': u'0',
u'body_src': u'some text1'}],
u'job_27302': [{u'auto_approve': u'0',
u'body_src': u'some text2'}],
u'job_27303': [{u'auto_approve': u'0',
u'body_src': u'some text3'}] }
I have this dictionary of lists.
how can I loop over it and get body_src
from the value list in each step? I tried
for k, d in data:
print d[k]
to get the list part, but it is saying too many values to unpack
...
Upvotes: 1
Views: 99
Reputation: 55469
You're getting that error message because when you iterate directly over a dict
you only get the keys.
So you could do this:
for k in data:
print data[k][0]['body_src']
output
some text1
some text3
some text2
Upvotes: 2
Reputation: 180401
d={ u'job_27301': [{u'auto_approve': u'0',
u'body_src': u'some text1'}],
u'job_27302': [{u'auto_approve': u'0',
u'body_src': u'some text2'}],
u'job_27303': [{u'auto_approve': u'0',
u'body_src': u'some text3'}] }
for k,v in d.iteritems(): # items in python 3
print(v[0]["body_src"])
Or just the values:
for v in d.itervalues(): # values in python 3
print(v[0]["body_src"])
Upvotes: 2
Reputation: 16556
In order to iterate over the dict (key,item)
, you can use data.items()
or iteritems()
:
>>> for k,d in data.iteritems():
... print d[0][u'body_src']
...
some text1
some text3
some text2
When doing for k,d in data:
you try to iterate over the keys only:
>>> for i in data:
... print i
...
job_27301
job_27303
job_27302
Upvotes: 1