Transforming a list into a dictionary 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'
    }
}
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.