Home > database >  Returning a subset of list and dictionaries, from a list of dictionaries
Returning a subset of list and dictionaries, from a list of dictionaries

Time:11-21

Im trying to return a subset of list of dictionaries, derived from a list of dictionaries.

Input:

dicts = [
    {'name': 'Sam', 'age': 12},
    {'name': 'Pete', 'age': 14}, 
    {'name': 'Sarah', 'age': 16}
]

Im trying to get this output:

res = [
    {'name': 'Sam'},
    {'name': 'Pete'}, 
    {'name': 'Sarah'}
]

So far i've been trying with this approach:


res = []

def new_dict(dicts):
    for i in range(len(dicts)):
        for k, v in dicts[i]:
            if dicts[i][k] == 'name'
                res.append(dicts[i][k] = v)

print(new_dict(dicts))

CodePudding user response:

With list comprehension you can do:

[{'name': x['name']} for x in dicts]

CodePudding user response:

The safer method (That won't fail if one of your dicts doesn't have a name value):

[{'name': x['name']} for x in dicts if 'name' in x]
  • Related