views:

56

answers:

1

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):
    ??
+3  A: 

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?

Alex Martelli
if it isn't in!
Blankman
`if x not in mydic` =)
katrielalex
how do I get the # of items in the dic?
Blankman
@Blankman, `len(mydic)`, of course. Have you even **looked** at the Python tutorial? You really should, you know!
Alex Martelli
i tried that and got an error...hmmm. (looking at the doc page actually, which makes it worse? )
Blankman
You might use `for x in range(len(mydic)):` if I'm correctly inferring what you're trying to do.
junkforce
@Blankman, if `len(mydic)` gives an error, then `mydic` is definitely not a dictionary (nor a list nor any other normal container).
Alex Martelli
what about setdefault() ?
magcius
@magcius, I consider `setdefault` a well-intentioned but failed experiment (and I had enough to do with its inception, even though I played a very minor role in it, that this can be taken as repentance on my part). `collections.defaultdict` does essentially what the `setdefault` method of dict was intended to do, _so_ much better.
Alex Martelli
+1 for the use of `auxset` instead of directly using the `mylist`.
jeffjose