PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 2, 2022

[FIXED] how can I add index as key value in a list of dict in python?

 November 02, 2022     dictionary, indexing, list, python     No comments   

Issue

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.


Solution

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}]


Answered By - joe
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing