Sandy
Sandy

Reputation: 263

how to update dictionary dynamically in python

I am trying to update dictionary dynamically

for I in range(0,4):
    var = method(I) # var = "abc:def:ghi:1234"
    [a,b,c,d]= var.split(':')
    d = d.rstrip('\n')
    rdict = {i:d}
    rdict = rdict .update({i:d})

But problem is if I print rdict, it is not printing. I,m missing some basic steps. Please help on this.

Upvotes: 1

Views: 278

Answers (1)

chepner
chepner

Reputation: 531075

rdict.update modifies the dictionary in-place and returns None. Don't assign that value back to rdict.

rdict = {}
for i in range(0,4):
    var = "abc:def:ghi:1234"
    [a,b,c,d]= var.split(':')
    d = d.rstrip('\n')
    rdict.update({i:d})

Most of the code in the loop is independent of i, and could be moved outside the loop. In fact, a much more idiomatic way to create rdict would be

rdict = dict((i, var.split(':')[3]) for i in range(4))

or

# Python 2.7 or later
rdict = {i: var.split(':')[3] for i in range(4)}

If var is dependent on i, then

rdict = {}
for i in range(4):
    a, b, c, d = method(i)
    d = d.rstrip('\n')
    rdict[i] = d   # More efficient than calling update

Upvotes: 5

Related Questions