Reputation: 2495
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
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
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
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