6

This seems to be a pretty common pattern:

for row in reader:
    c1=row[0]
    if ids.has_key(c1):
        id1=ids.get(c1)
    else:
        currid+=1
        id1=currid
        ids[c1]=currid

I want to know if there is a better way to achieve this. As far as single line if statements go, I could do this much:

id1=ids.get(c1) if ids.has_key(c1) else currid+1

But then I'm stuck with incrementing currid and sticking if the else case was executed and sticking c->id1 into the dictionary if the if condition passed.

5 Answers 5

4

If the ids start from 0:

for row in reader:
    id1 = ids.setdefault(row[0], len(ids))

(Aside: has_key is considered deprecated. Use x in d instead of d.has_key(x).)

2
  • Funny; I posted this answer earlier today and actually used this idiom only yesterday.
    – Fred Foo
    Mar 8, 2012 at 21:54
  • 1
    Like I said, common pattern ;)
    – Sid
    Mar 8, 2012 at 22:01
4

If you don't mind changing how ids is defined, then you could go with this (all in the standard library):

ids = collections.defaultdict (itertools.count ().next)

Usage is then very simple:

print (ids["lol"])
6
  • nice to know. I'm building a distance matrix so would rather have int ids. have a huge amt of data too.
    – Sid
    Mar 8, 2012 at 21:57
  • Very nice, but this also changes the dict's behavior because it will never again raise a KeyError. Still, +1.
    – Fred Foo
    Mar 8, 2012 at 21:59
  • @larsmans: not raising KeyErrors is the point of defaultdict. Mar 8, 2012 at 22:03
  • @Sid: This will give integer ids, starting with 0 and then incrementing by 1, as in your example. But as larsmans said, this will make the dictionary behave somewhat differently, of which you have to be aware if you use it.
    – user319799
    Mar 8, 2012 at 22:04
  • @doublep In my case this would have worked perfectly fine too as the type of ids is not a critical. Thanks.
    – Sid
    Mar 8, 2012 at 22:06
1
currid += c1 not in ids
id1 = ids.setdefault(c1, currid)
1
  • This doesn't store the new id.
    – Fred Foo
    Mar 8, 2012 at 21:52
0

Use this instead:

id1 = ids.get(cl, currid + 1)
0

A bit more pythonyc, with the same semantics:

for row in reader:
    c1 = row[0]
    if c1 not in ids:
        currid += 1
        ids[c1] = currid
    id1 = ids[c1]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.