【发布时间】:2021-07-13 04:03:37
【问题描述】:
以下是数据示例:
[{
'name': 'Age',
'p_value': '<0.001',
'ks_score': '0.07',
},
{
'name': 'peer_LM_Mean_SelfAware',
'p_value': '<0.001',
'ks_score': '0.06',
}]
我有超过 16,000 个字典,列表中有几个项目。我想要做的是从另一个包含旧名称和新名称的字典中替换此字典中 name 的值。
col_rename_list = {'Male': 'Male, n (%)',
'Age': 'Age, years',
'Baby_Boomers__1946_1964_': 'Baby Boomers (1946-1964), n (%)',
'Generation_X__1965_1980_': 'Generation X (1965-1980), n (%)',
'Generation_Y___Millennials__1981_1996_': 'Generation Y/Millennials (1981-1996), n (%)',
'Race_Asian': 'Asian, n (%)',
'peer_LM_Mean_SelfAware': 'Self-Awareness'
}
我该怎么做?我能想到的一种方法如下:
for d in dictionary_list:
for k,v in d.items():
if k == 'name':
if col_rename_list.get(v) is not None:
d[k] = col_rename_list.get(v)
这可行,但有没有更好更有效的方法来做到这一点?
【问题讨论】:
标签: python dictionary list-comprehension