1
\$\begingroup\$

I have a simple list and want to filter it by a specific key. But I guess my for loop solution is not an efficient way. I'm searching an other way or one best practice.

types = [
    {
        'name':'John',
        'surname':'Doe',
        'age':36,
        'type':'customer'
    },
    {
        'name':'Jane',
        'surname':'Doe',
        'age':31,
        'type':'supplier'
    }
]

Normally I'm iterating over on list and determining according to "type" field.

new_types = {}
for t in types:
    new_types[t['type']] = t

My purpose is also below but I'm looking another iterating and filtering way for upper loop. I have created the result and expectation is:

{
    'customer':{
        'type':'customer',
        'age':36,
        'surname':'Doe',
        'name':'John'
    },
    'supplier':{
        'type':'supplier',
        'age':31,
        'surname':'Doe',
        'name':'Jane'
    }
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ What do you expect as output if there are two items in types which have type='customer'? \$\endgroup\$
    – holroy
    Feb 25, 2016 at 16:00
  • \$\begingroup\$ Always I get just two elements in one list. For this reason the other circumstances are not important for my case. Otherwise needs to make an list for each elements of type. \$\endgroup\$
    – vildhjarta
    Feb 25, 2016 at 16:07

1 Answer 1

1
\$\begingroup\$

Whenever you have that pattern, use a dict comprehension.

new_types = {t['type']: t for t in types}

That is more elegant and expressive, but no more performant than your original code. No matter what, you need to transform every item in the list. There's not much you can do to change that fact.

\$\endgroup\$
5
  • \$\begingroup\$ Well. Is it rational to use lambda function for this case? \$\endgroup\$
    – vildhjarta
    Feb 25, 2016 at 16:02
  • \$\begingroup\$ What lambda are you talking about? \$\endgroup\$ Feb 25, 2016 at 16:03
  • \$\begingroup\$ I would say it is not proper for me because there is not conditional things. I imagined that I can use filter() with a lambda. \$\endgroup\$
    – vildhjarta
    Feb 25, 2016 at 16:31
  • \$\begingroup\$ There was no condition in your original code. \$\endgroup\$ Feb 25, 2016 at 16:32
  • \$\begingroup\$ Yes you are right. I just thought I could use. Thanks. \$\endgroup\$
    – vildhjarta
    Feb 25, 2016 at 16:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.