Home > Software design >  filtering python list/dictionary and retrieve value for selected key
filtering python list/dictionary and retrieve value for selected key

Time:11-10

working on Python script. I get a result that is list:

a = [{'S_RAF': {'C_C106': {'D_1103': 'AVE', 'D_1104': '3-AB3242'}}}, {'S_RAF': {'C_C106': {'D_1103': 'OI', 'D_1104': '31503302130'}}}, {'S_RAF': {'C_C106': {'D_1103': 'PQ', 'D_1104': 'IBAN3102495934895'}}}]

And I would like to get the value of Key: D_1104, when the value for key D_1103 is PQ.

what would be best way in python to get the value of this key in element S_RAF/C_C106/{D_1103=PQ}. function should return: IBAN3102495934895.

Thanks

I tried:

a[2]['C_C106']['D_1104']

but is not correct.

CodePudding user response:

Should do it:

a[2]['S_RAF']['C_C106']['D_1104'] # IBAN3102495934895

CodePudding user response:

You can iterate through the list and check the values in each dictionary like this:

for dictionary in a:
    if dictionary['S_RAF']['C_C106']['D_1103'] == 'PQ':
       iban = dictionary['S_RAF']['C_C106']['D_1104']

CodePudding user response:

Get ISBNs where D_1103 == "PQ".

ibans = [x["S_RAF"]["C_C106"]["D_1104"] for x in a if x["S_RAF"]["C_C106"]["D_1103"]=="PQ"]
ibans = ibans[0]  # "IBAN3102495934895"
  • Related