Lambda function for dict dict - Python

2

I would like to know if there is a possibility of using filter with a lambda function to select a conjunto de dados of a array de J SON in Python .

Example: I have the following JSON already as dict in Python , follows the structure. And I would like% with% filtrar which are of type dict's internos .

{'events': [{'event':'a', ...},{'event':'b',...},{'event':'a'...}]}

I would like something like:

list_a = dict(filter(lambda x: [events][][x] == 'a', data_json.items()))

I can not see a way to 'event' == 'a' the most internal dictionaries of this filtrar .

    
asked by anonymous 07.10.2018 / 04:58

1 answer

1

Inline generation of dictionaries is done through a dictionary comprehension :

data_json = {'events': [{'event':'a', 'foo': 'bar'}, {'event':'b', 'foo': 'baz'}, {'event':'a', 'foo': 'bax'}]}
dict_a = {key: list(filter(lambda x: x['event'] == 'a', lst)) for key, lst in data_json.items()}
print(dict_a)
# {'events': [{'event': 'a', 'foo': 'bar'}, {'event': 'a', 'foo': 'bax'}]}

You can also use a list comprehension instead of filter :

data_json = {'events': [{'event':'a', 'foo': 'bar'}, {'event':'b', 'foo': 'baz'}, {'event':'a', 'foo': 'bax'}]}
dict_a = {key: [item for item in lst if item['event'] == 'a'] for key, lst in data_json.items()}
print(dict_a)
# {'events': [{'event': 'a', 'foo': 'bar'}, {'event': 'a', 'foo': 'bax'}]}
    
07.10.2018 / 15:28