首页 > 解决方案 > Python list object mutation

问题描述

I have a python data structure which is a list of dict, like:

data = [
   {
       'user':{
          'name': 'INIT_NAME'
          'age': 18
       },
       'cart':{
          ...
       }
   },
   ...
]

my objective is to parse every single attr in the dict, so that i could replace the string with upper cap to a specified value. For example, i would like to parse the data structure above to:

data = [
   {
       'user':{
          'name': 'my name'
          'age': 18
       },
       'cart':{
          ...
       }
   },
   ...
]

of cause, i would do this by python code like:

for d in data:
  for type, attrs in d.items():
    for key, value in attrs.items():
      attrs[key] = parse_attr(value)

def parse_attr(value):
  if value == 'INIT_NAME':
    return 'my name'

Sure it will work, but sames it is not quite readable and little hard to knowing what is going on by a glance.

I just wonder are there any simplier way better than this? I am care about code readability therefore i am looking for a better approach. I am just new to python and just know the basic like decorator and syntactic sugar which is not helping in this case. Please let me know if you have any idea. Thank you

标签: pythonlistdictionary

解决方案


推荐阅读