Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to increment and assign ids from dictionary

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.

like image 767
Sid Avatar asked Mar 08 '12 21:03

Sid


People also ask

How do you append a dictionary as a value to another dictionary in python?

Append values to a dictionary using the update() method The Python dictionary offers an update() method that allows us to append a dictionary to another dictionary. The update() method automatically overwrites the values of any existing keys with the new ones.

How do you append an item to a list in a dictionary python?

Method 1: Using += sign on a key with an empty value In this method, we will use the += operator to append a list into the dictionary, for this we will take a dictionary and then add elements as a list into the dictionary.

Can we use append in dictionary?

We can make use of the built-in function append() to add elements to the keys in the dictionary. To add element using append() to the dictionary, we have first to find the key to which we need to append to.


1 Answers

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

like image 194
Fred Foo Avatar answered Sep 21 '22 10:09

Fred Foo