I'm trying to parse/loop through a deeply nested dictionary/tuple such as this:
#!/usr/bin/env python
movies = {
'in_bruges': {
'display': 'In Bruges',
'actors': {
'Colin Farrel': {
'age': '99',
'height': '160'
},
'Brendan Gleeson': {
'age': '88',
'height': '158'
}
# many more...
}
},
'fargo': {
'display': 'Fargo',
'actors': {
'William H. Macy': {
'age': '109',
'height': '120'
},
'Steve Buscemi': {
'age': '11',
'height': '118'
}
# many more...
}
}
# many more...
}
I can access individual fields just fine:
print(movies['in_bruges']['actors']['Brendan Gleeson']['age']);
88
But I'm having a hard time looping through the whole thing. This is what I have so far...
for movie, val in movies.iteritems():
print movie
for v in val.values():
print v
for x in v.values(): # <-- BREAKS HERE
print x
Error:
AttributeError: 'str' object has no attribute 'values'
I understand why it's breaking... just not sure how to fix it. Also, and probably more importantly, is there a better way to do this? This is a mix of a dictionary and a tuple (correct me if I'm wrong). Should I structure it differently? Or use a different method altogether? I'd rather not read it in from a csv or text...