Reputation: 694
I have a list of nested dictionaries that is a cached for finding returned results from a BBDD.
What I want is to check if a nested dict exists inside my list and return the value it has.
My dict had this structure:
cached_list= [{'session':'2019-02-03',
'country':'spain',
'isin': 'ES202121223'} , ...
}
For avoiding going throw all the values I did a nested dict inside my cached list:
list_cached = [{'2019-02-03':{'spain':'ES202121223'}} , ...]
As you can see it has the same structure but I am using key as values for checking if that structure exists.
My problem is that I am saving all that nested dict inside a list, and I dont know how to check if that structure exists in my list of nested dictionaries.
Any idea for solving it?
Thanks.
Upvotes: 0
Views: 605
Reputation: 12201
Adding an example answer with Pandas (not really an answer, but an example for handling a list of dicts, and using a multi-index to create the idea of a nested dict.)
>>> cached_list = [{'session': '2019-02-03', 'country': 'spain', 'isin': 'ES202121223'},
... {'session': '2019-02-03', 'country': 'italy', 'isin': 'IT202121223'}]
>>> import pandas as pd
>>> df = pd.DataFrame(cached_list)
>>> df
session country isin
0 2019-02-03 spain ES202121223
1 2019-02-03 italy IT202121223
>>> df = df.set_index(df.index, 'session')
>>> df
session country isin
0 2019-02-03 spain ES202121223
1 2019-02-03 italy IT202121223
>>> df['session'] = pd.to_datetime(df['session'])
>>> from datetime import datetime
>>> df[df['session'] == datetime(2019, 2, 3)]
session country isin
0 2019-02-03 spain ES202121223
1 2019-02-03 italy IT202121223
The set_index
part is not really necessary: leaving it out will just select directly on a data column.
Upvotes: 1
Reputation: 12201
Not the prettiest solution, but a variation on the following list-comprehension could work:
>>> list_cached = [{'2019-02-03':{'spain':'ES202121223'}}, 1, {'a': 1} ]
>>> [item for item in list_cached if isinstance(item, dict) and isinstance(list(item.values())[0], dict)]
[{'2019-02-03': {'spain': 'ES202121223'}}]
The two isinstance
clauses check if an item is a nested dict. Note that this still fails for an empty nested dict ({'2019-02-03': {}}
).
Upvotes: 1