简体   繁体   English

通过字典列表的键重新编码值

[英]Recodifying values by key of a list of dictionaries

I have a json object that is a list of dictionaries, that comes from an api.我有一个 json 对象,它是一个来自 api 的字典列表。 I'm looking for changing the values of certain keys of the json before inserting them into a database.在将它们插入数据库之前,我正在寻找更改 json 某些键的值。 The list looks like this:该列表如下所示:

[
  {
    'id': 1,
    'sex': 'Female'
    'status': 'Active'
  },
  {...},
]

The json always have all keys presented. json 总是显示所有键。 I want to change the string values of the keys for integers, since it would fit the database model:我想更改整数键的字符串值,因为它适合数据库模型:

[
  {
    'id': 1,
    'sex': 2
    'status': 1
  },
  {...},
]

I'm capable of changing one dictionary item using .update('key': recode_fun) or iterate through the whole list, but I don't see how to do both without several loops (loop through the range, list and dictionary).我能够使用.update('key': recode_fun)更改一个字典项或遍历整个列表,但我不知道如何在没有几个循环的情况下做到这两项(循环遍历范围、列表和字典)。 I'm trying to do it using a helper function:我正在尝试使用辅助函数来做到这一点:

def recode_sex(value):
    return {
      'Male': 1,
      'Female': 2,
    }.get(value, value)

Since there are multiple keys value that needs updated and want to keep the loops readable.由于有多个键值需要更新并希望保持循环可读。

You do not want a list of dictionaries but a dictionary of dictionaries.您不需要字典列表,而是需要字典字典。 Something like:就像是:

code_table = {
  'sex':
    {'Male': 1,
     'Female': 2
    },
  'status':
    {'Active': ...
    },
  ...
}

You can then build the recoded list with a simple comprehension:然后,您可以使用简单的理解来构建重新编码的列表:

recoded = [{k: code_table.get(k, {v: v})[v] for k,v in d.items()} for d in data]

If you already have the helper functions then you only need to loop once through each item of the list and modify all your key:value pairs:如果您已经有了辅助函数,那么您只需要遍历列表中的每一项并修改所有的键值对:

for i in list:
    i['key'] = recode_key(i['key'])
    i['anotherkey'] = recode_anotherkey(i['key'])
    i['yetanotherkey'] = recode_yetanotherkey(i['key'])

You would need to loop through the list once, touch all the keys that you need, and your helper function makes sure that you don't update the key twice or with another value.您需要遍历列表一次,触摸您需要的所有键,并且您的辅助函数确保您不会更新键两次或使用其他值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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