Home > Blockchain >  How to get specific value from specific key in Python
How to get specific value from specific key in Python

Time:10-25

jsonA = 
[ {'id': 'xxx1', 'serial': 'BPCE-RNHC-25G8', 'model': 'AlertTrace', 'subject': 'EMP004'}, 
{'id': 'xxx2', 'serial': 'XX-WWW-2XSFC', 'model': 'AlertTrace', 'subject': 'EMP005'}, 
{'id': 'xxx3', 'serial': 'VVV-ASD-CDSG', 'model': 'AlertTrace', 'subject': ''} ]

I have 3 json data and I want to retrieve data that subject is not null. Next, I should able to filter the result that only have two keys which are serial and subject.

Expected output:

jsonA = 
[ {'serial': 'BPCE-RNHC-25G8', 'subject': 'EMP004'}, 
{'serial': 'XX-WWW-2XSFC', 'subject': 'EMP005'} ]

I tried with this code: (but the output only show me the subject only. I need the both value from serial and subject)

Filter = [{'serial': dct['serial']} and {'subject': dct['subject']} for dct in jsonA if (dct['subject']) != None]

CodePudding user response:

Just do:

res = [{'serial': dct['serial'], 'subject': dct['subject']} for dct in jsonA if dct['subject']]
print(res)

Output

[{'serial': 'BPCE-RNHC-25G8', 'subject': 'EMP004'}, {'serial': 'XX-WWW-2XSFC', 'subject': 'EMP005'}]

In Python the truth value of None and "" is False, so you can use dct['subject'] directly in conditionals. For creating dictionaries, refer to the documentation.

CodePudding user response:

You can try with the following example code:

a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
       for key, value in a_dict.items():
            print(key, '->', value)

In your code you can try something like:

for key, value in jsonA.items():    
   if value != None:

return key

But im not completely sure:)

  • Related