I have a list of nested dicts, and would like to find the dict which contains a certain value then use that dict to find the values of the other keys in the dict. For example, I want to search the list for the MP_REFERENCE '123456', so that I can save the dict containing this string and find other values within it (eg. my_dict["OUTCOME_CODE"]["value"])
Asked
Active
Viewed 85 times
-1
-
1Duplicate of [Python list of dictionaries search](https://stackoverflow.com/questions/8653516/python-list-of-dictionaries-search) – mustaccio Aug 06 '20 at 17:27
2 Answers
1
In [64]: LIST = [
...: {
...: "RESPONSE_TYPE_CODE": {"value": "RNAGE"},
...: "OUTCOME_CODE": {"value": "ACCPT"},
...: "MP_REFERENCE": {"value": 338451},
...: "TRANSACTION_REFERENCE": {"value": "213527"},
...: "TRANSACTION_TYPE_CODE": {"value": "APPNT"},
...: "TRANSACTION_STATUS_CODE": {"value": "ACCPT"},
...: },
...: {
...: "RESPONSE_TYPE_CODE": {"value": "RNAGE"},
...: "OUTCOME_CODE": {"value": "ACCPT"},
...: "MP_REFERENCE": {"value": 519505},
...: "TRANSACTION_REFERENCE": {"value": "123456"},
...: "TRANSACTION_TYPE_CODE": {"value": "APPNT"},
...: "TRANSACTION_STATUS_CODE": {"value": "ACCPT"},
...: },
...: {
...: "RESPONSE_TYPE_CODE": {"value": "RNAGE"},
...: "OUTCOME_CODE": {"value": "REJCT"},
...: "MP_REFERENCE": {"value": 123456},
...: "TRANSACTION_REFERENCE": {"value": "475582"},
...: "TRANSACTION_TYPE_CODE": {"value": "DEAPP"},
...: "TRANSACTION_STATUS_CODE": {"value": "ACCPT"},
...: }
...: ]
In [63]: [d for d in LIST if d["MP_REFERENCE"]["value"] == 123456]
Out[63]:
[{'RESPONSE_TYPE_CODE': {'value': 'RNAGE'},
'OUTCOME_CODE': {'value': 'REJCT'},
'MP_REFERENCE': {'value': 123456},
'TRANSACTION_REFERENCE': {'value': '475582'},
'TRANSACTION_TYPE_CODE': {'value': 'DEAPP'},
'TRANSACTION_STATUS_CODE': {'value': 'ACCPT'}}]

bigbounty
- 16,526
- 5
- 37
- 65
1
Here is some code that iterates through "LIST" and saves the dict with the specifications you asked for into a variable called correct_dict. Note that I have renamed "LIST" to lst for simplicity.
lst = [
{
"RESPONSE_TYPE_CODE": {"value": "RNAGE"},
"OUTCOME_CODE": {"value": "ACCPT"},
"MP_REFERENCE": {"value": 338451},
"TRANSACTION_REFERENCE": {"value": "213527"},
"TRANSACTION_TYPE_CODE": {"value": "APPNT"},
"TRANSACTION_STATUS_CODE": {"value": "ACCPT"},
},
{
"RESPONSE_TYPE_CODE": {"value": "RNAGE"},
"OUTCOME_CODE": {"value": "ACCPT"},
"MP_REFERENCE": {"value": 519505},
"TRANSACTION_REFERENCE": {"value": "123456"},
"TRANSACTION_TYPE_CODE": {"value": "APPNT"},
"TRANSACTION_STATUS_CODE": {"value": "ACCPT"},
},
{
"RESPONSE_TYPE_CODE": {"value": "RNAGE"},
"OUTCOME_CODE": {"value": "REJCT"},
"MP_REFERENCE": {"value": 123456},
"TRANSACTION_REFERENCE": {"value": "475582"},
"TRANSACTION_TYPE_CODE": {"value": "DEAPP"},
"TRANSACTION_STATUS_CODE": {"value": "ACCPT"},
}]
correct_dict = {}
for dic in lst:
if dic["MP_REFERENCE"]["value"] == "123456":
correct_dict = dic

M-Chen-3
- 2,036
- 5
- 13
- 34