skip to Main Content

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


  1. Chosen as BEST ANSWER

    I feel like Jonathan's approach is best for this!

    [item['value'] for item in a if item['action_type'] == 'landing_page_view']


  2. for item in a:
        if item['action_type'] == 'landing_page_view':
            print(item['value'])
    

    Repeat for b and c.

    Login or Signup to reply.
  3. You can access it like you would normally but with the list and position in the begining

    example:

    lists = [{'hello':'world', 'bye':'world'}]
    print (lists[0]['hello'])
    lists[0]['hello'] = "user"
    print (lists[0]['hello'])
    

    output:

    world
    user
    
    Login or Signup to reply.
  4. A one-liner solution :

    [item['value'] for item in a if item['action_type'] == 'landing_page_view']
    
    Login or Signup to reply.
  5. Here’s another way of doing it for those who don’t like list comprehensions so much:

    from cherrypicker import CherryPicker
    picker = CherryPicker(a)
    picker(action_type='landing_page_view')['value'].get()
    

    Install cherrypicker with pip install --user cherrypicker. Read about more advanced usage in the docs: https://cherrypicker.readthedocs.io.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search