I am looping in python and want to add a key to a dictionary only if it isn’t already in the collection.
How can I do this?
mydic = {}
for x in range(100):
??
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For a dict, it’s easy and fast:
that is, just check with
not ininstead ofin.This is great for a dict. For a list, it’s going to be extremely slow (quadratic); for speed, you need to add an auxiliary set (hopefully all items in the list are hashable) before the loop, and check and update it in the loop. I.e.:
For a tuple, it’s impossible to add anything to it, or in any other way modify it, of course: tuples are immutable! Surely you know that?! So, why ask?