1

I have a list of dictionary and I want to get only a specific item from each dictionary. My data pattern is:

data = [
    {
        "_id": "uuid",
        "_index": "my_index",
        "_score": 1,
        "_source": {
            "id" : 1,
            "price": 100
        }
    },
    {
        "_id": "uuid",
        "_index": "my_index",
        "_score": 1,
        "_source": {
            "id" : 2,
            "price": 150
        }
    },
    {
        "_id": "uuid",
        "_index": "my_index",
        "_score": 1,
        "_source": {
            "id" : 3,
            "price": 90
        }
    }
]

My desired output:

formatted_data = [
    {
        "id": 1,
        "price": 100
    },
    {
        "id": 2,
        "price": 150
    },
    {
        "id": 3,
        "price": 90
    }
]

To formate data I have used iteration (for) like

formatted_data = []
for item in data:
    formatted_data.append(item['_source'])

In PHP I can use array_column() instead of for loop. So what will be the alternative of for in python3 in my case? Thanks in advance.

4

1 回答 1

3

您可以使用列表理解:

In [11]: [e['_source'] for e in data]
Out[11]: [{'id': 1, 'price': 100}, {'id': 2, 'price': 150}, {'id': 3, 'price': 90}]
于 2018-05-22T06:40:15.173 回答