how do i add key to my json list in python to an object with the same name?

Viewed 38

hello i got a problem and i'm not sure how to solve it :

i have a project where i'm recovering a json file via a request and making a list with the keys i need so it look a bit like this:

{
   "name":"Lucas White",
   "project":{
      "key_project":"EB-648",
      "name_status":"Open"
   }
},
{
   "name":"Lisa Booth",
   "project":{
      "key_project":"EB-647",
      "name_status":"Open"
   }
}
{
   "name":"Lucas White",
   "project":{
      "key_project":"EB-645",
      "name_status":"Development In Progress"
   }
},

here is my code in python

    entries = []
    entries.append({
                    "name":name ,
                    "project": {
                        "key_project":key_project,
                        "name_status":name_status
                    }
            },)

how do i make it so that Lucas get a list with all his project keys ?? also its my first question i hope it is clear cause english is not my first language

1 Answers

I would suggest the next approach. First, add all data to the map and then transform the map to the list. You can use "name" as a key in the map. Here is out of a head example:

elements = {}
for ...:
    ...
    if name not in elements:
    # we check if name is not in our dictionary and create new list for that name
        elements[name] = list()
    elements[name].append({
        "key_project":key_project,
        "name_status":name_status
    })
    # we append the new project to the list

# as a result we get a map with names as keys and a list of projects for that name as values

result_list = [{"name": k, "projects": v} for k, v in elements.items()]
# k - key - and we used "name" as key
# v - value - value is list of all projects
Related