Home > database >  Replace all keys and manipulate values in a python dict and construct a new dict in a list
Replace all keys and manipulate values in a python dict and construct a new dict in a list

Time:09-22

Dict to manipulate

     data =  {
          "homepage.services.service_title_1": "Web Development",
          "homepage.services.service_title_2": "App Development"
      }

The goal is to replace all data's keys with "key" and add new "content" keys having the value of the previous/original dict(data dict) and for each key replaced, push a new dict(with "key" prop and "content" prop) to a list as below.

Expected Output

    texts = [{
    "key": "homepage.services.service_title_1",
    "content": "Web Development"
    },
    {
    "key": "homepage.services.service_title_2",
    "content": "App Development"
     }]

CodePudding user response:

You can try in this way:

data =  {
          "homepage.services.service_title_1": "Web Development",
          "homepage.services.service_title_2": "App Development"
      }

texts = []
for i,j in data.items():
    new_obj = {}
    new_obj["key"] = i
    new_obj["content"] = j
    texts.append(new_obj)
    
print(texts)
  • Related