Blankman
Blankman

Reputation: 267220

in a loop, only add to a dictionary or list or tuple if doesn't contains the key

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

Upvotes: 1

Views: 7742

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 882421

For a dict, it's easy and fast:

for x in range(100):
  if x not in mydic:
    mydic[x] = x  # or whatever value you want

that is, just check with not in instead of in.

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

auxset = set(mylist)
for x in range(100):
  if x not in auxset:
    auxset.add(x)
    mylist.append(x)  # or whatever

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?

Upvotes: 5

Related Questions