I’m pulling data out from the facebook API, what it returns is essentially a nested JSON looking file.
I’ve piped the data into the a pandas dataframe and one of the columns has returned a series of dictionaries nested in a list. (see examples in the code below).
How on Earth do I extract the values from each variable (i.e. a, b, c) when the action_type = landing_page_view?
i.e. in variable a, how do I extract the value when searching for specific action types?
i.e. return 44, 96 and 116 when I want to search the variables for ‘landing_page_view’?
I’ve tried various for loops and things of that nature but I am not having any luck. I’m at a loss…
a = [{'action_type': 'landing_page_view', 'value': '44'}, {'action_type': 'link_click', 'value': '102'}, {'action_type': 'post_reaction', 'value': '5'}, {'action_type': 'post_engagement', 'value': '107'}, {'action_type': 'page_engagement', 'value': '107'}]
b = [{'action_type': 'comment', 'value': '1'}, {'action_type': 'landing_page_view', 'value': '96'}, {'action_type': 'link_click', 'value': '285'}, {'action_type': 'post_reaction', 'value': '25'}, {'action_type': 'post_engagement', 'value': '311'}, {'action_type': 'page_engagement', 'value': '311'}]
c = [{'action_type': 'post_reaction', 'value': '11'}, {'action_type': 'landing_page_view', 'value': '116'}, {'action_type': 'link_click', 'value': '319'}, {'action_type': 'post_engagement', 'value': '330'}, {'action_type': 'page_engagement', 'value': '330'}]
5
Answers
I feel like Jonathan's approach is best for this!
[item['value'] for item in a if item['action_type'] == 'landing_page_view']
Repeat for
b
andc
.You can access it like you would normally but with the list and position in the begining
example:
output:
A one-liner solution :
Here’s another way of doing it for those who don’t like list comprehensions so much:
Install
cherrypicker
withpip install --user cherrypicker
. Read about more advanced usage in the docs: https://cherrypicker.readthedocs.io.