Python 基于另一个字典键值对更新列表中的字典键

Python 基于另一个字典键值对更新列表中的字典键,python,list,dictionary,Python,List,Dictionary,我有一个列表,里面有嵌套的字典,还有一个字典和相应的密钥对值。 我试图将dict2中的键映射到列表中字典元素的键 list = [{'name': 'Megan', 'Age': '28', 'occupation': 'yes', 'race': 'american', 'children': 'yes'}, {'name': 'Ryan', 'Age': '25', 'occupation': 'no', 'race': 'american', 'intern': 'yes'}] 包含正确

我有一个列表,里面有嵌套的字典,还有一个字典和相应的密钥对值。 我试图将dict2中的键映射到列表中字典元素的键

list = [{'name': 'Megan', 'Age': '28', 'occupation': 'yes', 'race': 'american', 'children': 'yes'}, {'name': 'Ryan', 'Age': '25', 'occupation': 'no', 'race': 'american', 'intern': 'yes'}]
包含正确键的相应词典如下所示

dict_map = {'occupation': 'service', 'intern': 'employee', 'race': 'ethnicity'}
到目前为止,我还不熟悉python,我正在尝试遍历stackoverflow页面,以获得一个输出,虽然也尝试了几次,但到目前为止还无法获得所需的结果。 我的壁橱里有这个

最终输出应为:


 [{'name': 'Megan', 'Age': '28', 'service': 'yes', 'ethnicity': 'american', 'children': 'yes'}, {'name': 'Ryan', 'Age': '25', 'service': 'no', 'ethnicity': 'american', 'employee': 'yes'}]


使用列表理解和
dict.get

Ex:

lst = [{'name': 'Megan', 'Age': '28', 'occupation': 'yes', 'race': 'american', 'children': 'yes'}, {'name': 'Ryan', 'Age': '25', 'occupation': 'no', 'race': 'american', 'intern': 'yes'}]
dict_map = {'occupation': 'service', 'intern': 'employee', 'race': 'ethnicity'}
result = [{dict_map.get(k, k): v for k, v in i.items()} for i in lst]            
print(result)
[{'Age': '28',
  'children': 'yes',
  'ethnicity': 'american',
  'name': 'Megan',
  'service': 'yes'},
 {'Age': '25',
  'employee': 'yes',
  'ethnicity': 'american',
  'name': 'Ryan',
  'service': 'no'}]
输出:

lst = [{'name': 'Megan', 'Age': '28', 'occupation': 'yes', 'race': 'american', 'children': 'yes'}, {'name': 'Ryan', 'Age': '25', 'occupation': 'no', 'race': 'american', 'intern': 'yes'}]
dict_map = {'occupation': 'service', 'intern': 'employee', 'race': 'ethnicity'}
result = [{dict_map.get(k, k): v for k, v in i.items()} for i in lst]            
print(result)
[{'Age': '28',
  'children': 'yes',
  'ethnicity': 'american',
  'name': 'Megan',
  'service': 'yes'},
 {'Age': '25',
  'employee': 'yes',
  'ethnicity': 'american',
  'name': 'Ryan',
  'service': 'no'}]
你可以试试这个:

请注意,我将您的列表重命名为
lst
list
是一种您永远不应该覆盖的类型!)