0

original

[{'l1Key': 'L1_SHARE', 'l2Key': None}, {'l1Key': 'L1_BROWSE_SOURCE', 'l2Key': None}, {'l1Key': 'L1_BLOCK_SOURCE', 'l2Key': None}, {'l1Key': 'L1_HIDE_NEWS', 'l2Key': None}, {'l1Key': 'NA', 'l2Key': 'HTML_2'}, {'l1Key': 'L1_SHOW_LESS', 'l2Key': 'HTML_2'}, {'l1Key': 'L1_SHOW_MORE', 'l2Key': None}]

expected answer

[{'l1Key': 'L1_SHARE'}, {'l1Key': 'L1_BROWSE_SOURCE'}, {'l1Key': 'L1_BLOCK_SOURCE', }, {'l1Key': 'L1_HIDE_NEWS'}, {'l1Key': 'NA', 'l2Key': 'HTML_2'}, {'l1Key': 'L1_SHOW_LESS', 'l2Key': 'HTML_2'}, {'l1Key': 'L1_SHOW_MORE'}]

i have tried with few codes but i am not getting as expected

[d for d in arr if all(d.values())]
[{'l1Key': 'NA', 'l2Key': 'HTML_2'}, {'l1Key': 'L1_SHOW_LESS', 'l2Key': 'HTML_2'}] //wrong as other key value pairs are all deleted if one of the keys is none or null

3 Answers 3

2
d = [{'l1Key': 'L1_SHARE', 'l2Key': None}, {'l1Key': 'L1_BROWSE_SOURCE', 'l2Key': None}, {'l1Key': 'L1_BLOCK_SOURCE', 'l2Key': None}, {'l1Key': 'L1_HIDE_NEWS', 'l2Key': None}, {'l1Key': 'NA', 'l2Key': 'HTML_2'}, {'l1Key': 'L1_SHOW_LESS', 'l2Key': 'HTML_2'}, {'l1Key': 'L1_SHOW_MORE', 'l2Key': None}]
clean_d = []
for dict in d:
  clean_d.append({k: v for k, v in dict.items() if v is not None})
Sign up to request clarification or add additional context in comments.

Comments

1

One-liner using list comprehension :

original = [{'l1Key': 'L1_SHARE', 'l2Key': None}, {'l1Key': 'L1_BROWSE_SOURCE', 'l2Key': None}, {'l1Key': 'L1_BLOCK_SOURCE', 'l2Key': None}, {'l1Key': 'L1_HIDE_NEWS', 'l2Key': None}, {'l1Key': 'NA', 'l2Key': 'HTML_2'}, {'l1Key': 'L1_SHOW_LESS', 'l2Key': 'HTML_2'}, {'l1Key': 'L1_SHOW_MORE', 'l2Key': None}]
expected = [{k: v for (k, v) in i.items() if v not in [None, '']} for i in original]

gives

[{'l1Key': 'L1_SHARE'}, {'l1Key': 'L1_BROWSE_SOURCE'}, {'l1Key': 'L1_BLOCK_SOURCE'}, {'l1Key': 'L1_HIDE_NEWS'}, {'l1Key': 'NA', 'l2Key': 'HTML_2'}, {'l1Key': 'L1_SHOW_LESS', 'l2Key': 'HTML_2'}, {'l1Key': 'L1_SHOW_MORE'}]

Checking membership like v not in [...] gives you flexibility to filter with more options.

1 Comment

@vinaykn Please accept this answer (or any other) if it solved your problem
1

[d for d in arr if all(d.values())]

In this line, you are selecting only those dictionaries which have all values that evaluate to a truthy. So you are missing the whole dictionary even if one value is None in your output.

You can delete the keys in place as follows without creating new dicts.

for curr in d:
    to_delete = [k for k, v in curr.items() if not v]
    for k in  to_delete:
       del curr[k]

Comments

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.