Rahul Sharma
Rahul Sharma

Reputation: 2495

Add increasing number in a list of dictionaries

I have a list of dictionaries

payloads = [{"a":20},{"b":20},{"c":20},{"d":20}]

and a static number, let's assume it is 2000

I want to add this number in first dictionary and a +1 in the following dictionaries for e.g. 2001 in 2nd dict, 2003 in 3rd and so on ( depending upon the length of dictionary)

I tried:

t_no = 2000
for p in payloads:
    for i  in range(len(payloads)):
        p['no'] = t_no + i
        break

but it gives the same output in every dictionary

Output:

[{'a': 20, 'no': 2000},
 {'b': 20, 'no': 2000},
 {'c': 20, 'no': 2000},
 {'d': 20, 'no': 2000}]

Desired Output

[{'a': 20, 'no': 2000},
 {'b': 20, 'no': 2001},
 {'c': 20, 'no': 2002},
 {'d': 20, 'no': 2003}]

How do I do this?

Upvotes: 0

Views: 57

Answers (3)

U13-Forward
U13-Forward

Reputation: 71610

You could try the following dictionary comprehension with dictionary unpacking **. I also use str.rjust. Here is the code:

>>> payloads = [{"a":20},{"b":20},{"c":20},{"d":20}]
>>> [{**v, 'no': int(str(list(v.values())[0]) + str(i).rjust(2, '0'))} for i, v in enumerate(payloads)]
[{'a': 20, 'no': 2000}, {'b': 20, 'no': 2001}, {'c': 20, 'no': 2002}, {'d': 20, 'no': 2003}]
>>> 

Upvotes: 0

abc
abc

Reputation: 11929

You can iterate over them using enumerate with 2000 as start.

>>> for idx, payload in enumerate(payloads,2000):
...     payload["no"]=idx
... 
>>> payloads
[{'a': 20, 'no': 2000}, {'b': 20, 'no': 2001}, {'c': 20, 'no': 2002}, {'d': 20, 'no': 2003}]

Upvotes: 4

Tomalak
Tomalak

Reputation: 338326

payloads = [{"a":20},{"b":20},{"c":20},{"d":20}]
t_no = 2000

for p in payloads:
    p['no'] = t_no
    t_no += 1

Upvotes: 3

Related Questions