'Filter nested dictionaries to second time key name appears, python
I would like to filter custom_fields1 so that the only remaining items are the ones who have 'Value' = 'Ja' below the line 'Name' = 'GPP' (and not below the first 'Name' key 'Name': 'Informationen'). Does anyone know how to efficiently filter through the dictionary? I am happy for every tip!
custom_fields1 =
[(44,
{'@odata.context': 'http://api.hellohq.io/v1/$metadata#CustomFields',
'value': [{'Name': 'Informationen',
'Value': '',
'Type': 'TextMultiline',
'Id': 18020,
'CreatedBy': 0,
'UpdatedBy': 0,
'CreatedOn': None,
'UpdatedOn': None},
{'Name': 'GPP',
'Value': 'Ja',
'Type': 'DropdownCheckbox',
'Id': 18049,
'CreatedBy': 0,
'UpdatedBy': 0,
'CreatedOn': None,
'UpdatedOn': None}]}),
(45,
{'@odata.context': 'http://api.hellohq.io/v1/$metadata#CustomFields',
'value': [{'Name': 'Informationen',
'Value': '',
'Type': 'TextMultiline',
'Id': 18020,
'CreatedBy': 0,
'UpdatedBy': 0,
'CreatedOn': None,
'UpdatedOn': None},
{'Name': 'GPP',
'Value': 'Ja',
'Type': 'DropdownCheckbox',
'Id': 18049,
'CreatedBy': 0,
'UpdatedBy': 0,
'CreatedOn': None,
'UpdatedOn': None}]}),
(46,
{'@odata.context': 'http://api.hellohq.io/v1/$metadata#CustomFields',
'value': [{'Name': 'Informationen',
'Value': '',
'Type': 'TextMultiline',
'Id': 18020,
'CreatedBy': 0,
'UpdatedBy': 0,
'CreatedOn': None,
'UpdatedOn': None},
{'Name': 'GPP',
'Value': 'Nein',
'Type': 'DropdownCheckbox',
'Id': 18049,
'CreatedBy': 0,
'UpdatedBy': 0,
'CreatedOn': None,
'UpdatedOn': None}]}))]
```
Solution 1:[1]
Your structure is sooo nested! Let's break it step by step.
- It's a list, so we want to iterate over it
for field in custom_field:
<I have an element>
- What the element is? Its a tuple and second element is what interest me
dict1 = field[1] - Now I have a dictionary, where value is what interest me most
values1 = dict['value'] - Oh, is it list again? Let's iterate again!
for dict_value in values1:
<this is the dict I need!>
- I got proper dict, now I just need to check my conditions
def check(dict_value):
return dict_value["name"] == ... and dict_value["Value"] == ...
How to do filtering based on that? You can use list filtering
[dict_value for dict_value in values1 if check(dict_value)]
And assign it to "value" key of outer dict.
Other option could be deleting records with del that does not satisfy our check.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kosciej16 |
