2
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]

2 Answers 2

2

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:)

Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

Oh, that mean i need to use , instead of and ?
@WEIZHUANGGOH In this particular case of building a dictionary yes, there other ways but this is the best one
Alright thanks for correcting me , i will mark this as answer in 11 minutes later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.