0

Goal: Have a dictionary-comprehension that removes a given key, if its respective value is "empty".

Empty means anything such as: [], 0, None, 0.0, "" etc.

Code:

thisdict =  {
  "brand": "Ford",
  "model": "Mustang",
  "year": ''  # [], 0, None, 0.0, "" etc.
}
print(thisdict)

thisdict = {val for key, val in thisdict.items() if val}  # Attempt

Please let me know if there is anything else I can add to post to help further clarify.

1
  • Will not do again in future, thank you Commented Nov 17, 2021 at 14:22

2 Answers 2

2

This

thisdict = {val for key, val in thisdict.items() if val}

is set-comprehension, if you need dict-comprehension do

thisdict = {key:val for key, val in thisdict.items() if val}

See PEP 274 for further discussion of Dict Comprehensions

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

1 Comment

Ahh thank you! Just as @Sayse pointed out
2

You can use built in method of python Dictionary(get)

{key:value for key,value in thisdict.items() if thisdict.get(key)}

2 Comments

How might I tell which out of yours and @Daweo 's would run quicker? I do have a fairly large dictionary. More out of curiosity
i think the @@Daweo 's code would run quicker but am not sure.

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.