Pythonic way to increase and assign identifiers from a dictionary

This seems like 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 for one line, if the statements go, I could do so much:

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

But then I got stuck with currency increment and gluing if the else case was fulfilled and inserted c-> id1 into the dictionary if the if condition passed.

+6
source share
5 answers

If identifiers begin with 0:

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

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

+5
source

If you don't mind changing the way you define ids , you can go with this (all in the standard library):

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

Using is very simple:

 print (ids["lol"]) 
+4
source
 currid += c1 not in ids id1 = ids.setdefault(c1, currid) 
+1
source

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] 
0
source

Use this instead:

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

Source: https://habr.com/ru/post/910284/


All Articles