How to extract strings after a specific named string

Viewed 29

I want to extract strings with full names after 'display': while removing the braces {} within the list.

Here is some data:

[{'display': 'Max Aarons', 'first': 'Max', 'last': 'Aarons'},
 {'display': 'Abdul Rahman Baba', 'first': 'Abdul Rahman', 'last': 'Baba'},
 {'display': 'Tammy Abraham', 'first': 'Tammy', 'last': 'Abraham'},
 {'display': 'Che Adams', 'first': 'Che', 'last': 'Adams'},
 {'display': 'Adrián', 'first': 'Adrián', 'last': 'San Miguel del Castillo'}]

I have tried using split after look at some articles:

[it.split for it in x['display']]

gives the error:

TypeError: list indices must be integers or slices, not str

I must be approaching this wrongly - any help would be appreciated!

Expected output:

['Max Aarons', 'Abdul Rahman Baba', 'Che Adams', 'Adrian San Miguel del Castillo']
2 Answers

You're indexing the entire list as if it's one of the dictionaries. Do this instead:

full_names = [it["display"] for it in x]

The data:

x = [
    {"display": "Max Aarons", "first": "Max", "last": "Aarons"},
    {"display": "Abdul Rahman Baba", "first": "Abdul Rahman", "last": "Baba"},
    {"display": "Tammy Abraham", "first": "Tammy", "last": "Abraham"},
    {"display": "Che Adams", "first": "Che", "last": "Adams"},
    {"display": "Adrián", "first": "Adrián", "last": "San Miguel del Castillo"},
]

List comprehension:

[i["display"] for i in x]

Output:

['Max Aarons', 'Abdul Rahman Baba', 'Tammy Abraham', 'Che Adams', 'Adrián']
Related