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.
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.
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.
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.
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)
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With