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:
stored.append(value['field'])
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']
If you just need to gather those strings in a list but you are not constrained to arrange them in a specific order, this should work:
>>> from itertools import chain
>>> [x['field'] for x in chain(*values.values())]
['course_code', 'prefix', 'suffix', 'student_email']
The core element of the snippet above is the function itertools.chain().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With