Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:
    stored.append(value['field'])

And it's throwing:

TypeError: string indices must be integers

How can I make this work?

like image 845
Modelesq Avatar asked Feb 23 '26 21:02

Modelesq


2 Answers

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']
like image 60
Psidom Avatar answered Feb 25 '26 09:02

Psidom


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().

like image 33
Tonechas Avatar answered Feb 25 '26 11:02

Tonechas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!