Lambda function for Dict Dict - Python

Asked

Viewed 166 times

2

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

Example: I have the following JSON already as dict in the Python, follows the structure. And would like to filtrar the dict's internos who are of the type 'event' == 'a'.

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

I’d like something like:

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

I can’t seem to see a way filtrar the most internal dictionaries of this 'events'.

  • What do you want in return of this filter ???

  • I would like to get all the contents of the array of 'Events' that have 'Event' = 'a' .

  • Only by using lambda ?

  • Yes, that’s the question.

  • Try f = filter(lambda x: x['Event'] ='a',dic['Events'])

1 answer

1

The generation inline of dictionaries is made 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 the 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'}]}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.