Home > Software engineering >  how can I add index as key value in a list of dict in python?
how can I add index as key value in a list of dict in python?

Time:10-20

I have a list like below -

[{'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z'}, {'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z'},
{'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z'}]

Need to add index key and its value in these three records. Expected output -

[{'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z','index':0}, {'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z','index':1},
{'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z','index':2}]

Please help.

CodePudding user response:

Try:

lst = [
    {"amount": 1100000, "target": 120000, "time": "2022-09-30T00:00:00.000Z"},
    {"amount": 1100000, "target": 120000, "time": "2022-09-30T00:00:00.000Z"},
    {"amount": 1100000, "target": 120000, "time": "2022-09-30T00:00:00.000Z"},
]

for idx, d in enumerate(lst):
    d["index"] = idx

print(lst)

Prints:

[
    {
        "amount": 1100000,
        "target": 120000,
        "time": "2022-09-30T00:00:00.000Z",
        "index": 0,
    },
    {
        "amount": 1100000,
        "target": 120000,
        "time": "2022-09-30T00:00:00.000Z",
        "index": 1,
    },
    {
        "amount": 1100000,
        "target": 120000,
        "time": "2022-09-30T00:00:00.000Z",
        "index": 2,
    },
]

CodePudding user response:

lst = [
{"amount": 1100000, "target": 120000, "time": "2022-09-30T00:00:00.000Z"},
{"amount": 1100000, "target": 120000, "time": "2022-09-30T00:00:00.000Z"},
{"amount": 1100000, "target": 120000, "time": "2022-09-30T00:00:00.000Z"},
]
for i in range(len(lst)):
    lst[i]['index']=i
print(lst)

Output

[{'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z', 'index': 0}, {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z', 'index': 1}, {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z', 'index': 2}]
  • Related