Modelesq Modelesq - 3 months ago 4x
Python Question

getting specific dict property values from multiple lists

Say I have a Dict that looks like so...

values = {
'student': [{
'field': 'prefix',
'description': 'First name'
'field': 'suffix',
'description': 'Last name'
'field': 'student_email',
'description': 'Email address'
'classes': [{
'field': 'course_code',
'description': 'Course code'


I'm trying to get

['prefix', 'suffix', 'student_email', 'course_code']

But I'm trying to do so without loops in loops.

So this is what I have:

stored = [] # store the field values in a list
for value in values:

And it's throwing:

TypeError: string indices must be integers

How can I make this work?


You get the error because the dictionary is one level deeper than your loop, and you can call items() on the dictionary to get the values part:

[v1['field'] for k, v in values.items() for v1 in v]
# ['prefix', 'suffix', 'student_email', 'course_code']