Home > Net >  How to get value from list of dictionaries based on specific key value which does not exist in all d
How to get value from list of dictionaries based on specific key value which does not exist in all d

Time:10-05

I have a list of dictionaries that is like this:

{'name': ['Sam'], 'where': ['London']},
{'name': ['Jon'], 'where': ['NY']},
{'name': ['Jon'], 'hobby': ['fifa']},
{'Age': ['20'], 'Country': ['US']},

I do have a dictionary like this that could have a lot of same keys but a lot doesn't have that key too. As in above example, we have name key in first 3, but we don't have name key in the 4th. I am trying to get a list of all values that has key 'name'.

Thanks

CodePudding user response:

What you want is unclear (nor the link to or ).

If you simply want the values of name when those exist:

l = [{'name': ['Sam'], 'where': ['London']},
     {'name': ['Jon'], 'where': ['NY']},
     {'name': ['Jon'], 'hobby': ['fifa']},
     {'Age': ['20'], 'Country': ['US']},]

out = [d['name'] for d in l if 'name' in d]
# [['Sam'], ['Jon'], ['Jon']]

# or as flat list
out = [name for d in l if 'name' in d for name in d['name']]
# ['Sam', 'Jon', 'Jon']

# or just the first name
out = [d['name'][0] for d in l if 'name' in d]
# ['Sam', 'Jon', 'Jon']

CodePudding user response:

Here is a way to extract all names:

data = [
    {'name': ['Sam'], 'where': ['London']},
    {'name': ['Jon'], 'where': ['NY']},
    {'name': ['Jon'], 'hobby': ['fifa']},
    {'Age': ['20'], 'Country': ['US']},
]

names = [item['name'][0] for item in data if 'name' in item]
print(names)

Result:

['Sam', 'Jon', 'Jon']

CodePudding user response:

I assume your data is a list of dicts.

data = [{'name': ['Sam'], 'where': ['London']},
{'name': ['Jon'], 'where': ['NY']},
{'name': ['Jon'], 'hobby': ['fifa']},
{'Age': ['20'], 'Country': ['US']},]

You can get a sub list of all elements with a name key like this:

output = [elem for elem in data if elem.get("name")]

CodePudding user response:

There are many ways to do this. One would be:

_list = [{'name': ['Sam'], 'where': ['London']},
{'name': ['Jon'], 'where': ['NY']},
{'name': ['Jon'], 'hobby': ['fifa']},
{'Age': ['20'], 'Country': ['US']}]

print(*(name for d in _list if (name := d.get('name'))))

Output:

['Sam'] ['Jon'] ['Jon']

CodePudding user response:

You can try a list expression:

all_dicts = [{'name': ['Sam'], 'where': ['London']},
{'name': ['Jon'], 'where': ['NY']},
{'name': ['Jon'], 'hobby': ['fifa']},
{'Age': ['20'], 'Country': ['US']}]

dicts_with_name = [d.values() for d in all_dicts if 'name' in d.keys() ]

This extracts all values (for all keys) of those dictionaries in the list that have a name field. If you want the key, value pairs, you can d.items() instead of d.values()

  • Related