简体   繁体   中英

Elegant way of iterating list of dict python

I have a list of dictionary as below. I need to iterate the list of dictionary and remove the content of the parameters and set as an empty dictionary in sections dictionary.

input = [
    {
        "category":"Configuration",
        "sections":[
            {
                "section_name":"Global",
                "parameters":{
                    "name":"first",
                    "age":"second"
                }
            },
            {
                "section_name":"Operator",
                "parameters":{
                    "adrress":"first",
                    "city":"first"
                }
            }
        ]
    },
    {
        "category":"Module",
        "sections":[
            {
                "section_name":"Global",
                "parameters":{
                    "name":"first",
                    "age":"second"
                }
            }
        ]
    }
]

Expected Output:

[
   {
      "category":"Configuration",
      "sections":[
         {
            "section_name":"Global",
            "parameters":{}
         },
         {
            "section_name":"Operator",
            "parameters":{}
         }
      ]
   },
   {
      "category":"Module",
      "sections":[
         {
            "section_name":"Global",
            "parameters":{}
         }
      ]
   }
]

My current code looks like below:

category_list = []
for categories in input:
    sections_list = []
    category_name_dict = {"category": categories["category"]}
    for sections_dict in categories["sections"]:
        section = {}
        section["section_name"] = sections_dict['section_name']
        section["parameters"] = {}
        sections_list.append(section)
        category_name_dict["sections"] = sections_list
    category_list.append(category_name_dict)

Is there any elegant and more performant way to do compute this logic. Keys such as category, sections, section_name, and parameters are constants.

The easier way is not to rebuild the dictionary without the parameters , just clear it in every section:

for value in values:
    for section in value['sections']:
        section['parameters'] = {}

Code demo

Elegance is in the eye of the beholder, but rather than creating empty lists and dictionaries then filling them why not do it in one go with a list comprehension :

category_list = [
    {
        **category,
        "sections": [
            {
                **section,
                "parameters": {},
            }
            for section in category["sections"]
        ],
    }
    for category in input
]

This is more efficient and (in my opinion) makes it clearer that the intention is to change a single key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM