Home > other >  I am facing little problem with lists and dicts in python
I am facing little problem with lists and dicts in python

Time:09-13

I have a list of a dict objects in python, that I am getting from the DB, and it is coming like this, even the "a", "b" and "c" header are coming from db too, and I need to format this to the second pattern, so then I can make use of it

[
{
    "a": 3,
    "name": "12-09-2022"
},
{
    "b": 16,
    "name": "09-09-2022"
},
{
    "b": 2,
    "name": "10-09-2022"
},
{
    "b": 25,
    "name": "12-09-2022"
},
{
    "c": 14,
    "name": "12-09-2022"
},
{
    "c": 1,
    "name": "13-09-2022"
}
]

then I have to format it to this:

[
 {
  "a": 0,
  "b": 16,
  "c": 0,
  "name": "09-09-2022"
 },
 {
  "a": 0,
  "b": 2,
  "c": 0,
  "name": "10-09-2022"
 },
 {
  "a": 3,
  "b": 25,
  "c": 14,
  "name": "12-09-2022"
 },
 {
  "a": 0,
  "b": 0,
  "c": 1,
  "name": "13-09-2022"
 }
]

hint: these data, even the "a","b" and "c" is coming from the db

CodePudding user response:

This may be something to do with your database and how you are querying it, which would likely be easier to solve, but if you want a rather "smelly" way of changing the format the below code should work:

#create new empty list
new_list = []

#loop over the original list
for dictionary in original_list:

    #extract the keys to the dictionary
    dictionary_keys = dictionary.keys()
    
    #create a boolean to hold if the name is in the new list
    in_new_list = False
    
    #loop over dictionaries in new list
    for new_dictionary in new_list:
        #if the names match
        if new_dictionary["name"] == dictionary["name"]:
           #set that they match
           in_new_list = True
           #then add the data from the old dictionary to the new
           for key in dictionary_keys:
               if key != "name":
                  new_dictionary[key] = dictionary[key]
    
    #otherwise just add the dictionary
    if in_new_list == False:
       new_list.append(dictionary)
        

  • Related