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

Question:

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

Asked By: johnoula

||

Answers:

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)

If the data is in list of dicts form, use this method

data =  [{
          "homepage.services.service_title_1": "Web Development",
          "homepage.services.service_title_2": "App Development"
      },{
          "homepage.services.service_title_1": "Mobile Development",
          "homepage.services.service_title_2": "Tab Development"
      }]

texts = []
for item in data:
    for i,j in item.items():
        new_obj = {}
        new_obj["key"] = i
        new_obj["content"] = j
        texts.append(new_obj)
    
print(texts)
Answered By: SAI SANTOSH CHIRAG