Reputation: 307
So I'm trying to iterate over a dictionary object in python and all I'm getting is list out of index error. Here is what my list looks like -
test_list = {"1":[{"1":[{"a":"100","b":"200"}],"2":[{"a":"300","b":"400"}]}]}
And here is the code -
for counter in range(len(test_list)):
print test_list['1'][counter]
Any idea why am I getting that error?
EDIT: I want to access all of a & b elements in test_list
Upvotes: 0
Views: 4171
Reputation: 47199
Nested dicts within lists, awesome.
I did the following, which can be modified to access the items needed.
In [21]: inside_dict = test_list['1'][0]
In [22]: for key,val in inside_dict.items():
print '{} contains'.format(key)
for key2, val2 in val[0].items():
print '\t{}: {}'.format(key2, val2)
Out[22]:
1 contains
a: 100
b: 200
2 contains
a: 300
b: 400
Upvotes: 1
Reputation: 428
python 3.2
t = {"1":[{"1":[{"a":"100","b":"200"}],"2":[{"a":"300","b":"400"}]}]}
res=[v["a"] for x in t.values() for p in x for y in p.values() for v in y] # values for a
Upvotes: 1
Reputation: 307
So here is the answer
for key, val in test_list['1'][0].items():
print key, val[0]['a']
print key, val[0]['b']
Upvotes: 0
Reputation: 13870
for k,v in test_list.items():
print v[0]['1']
Ok, maybe this help:
for c in test_list:
for v in test_list[c]:
print v['1']
print v['2']
Upvotes: 1
Reputation: 251408
Your code doesn't raise an error for me. If you want the first a and b elements, you would need:
for key, val in test_list['1'][0]['1'][0].items():
print key, val
Needless to say, that is rather convoluted. What you have is a dictionary in a list in a dictionary in a list in a dictionary. Why are you using this data structure? There is almost certainly a simpler way to represent your data.
Upvotes: 1