【问题标题】:How to replace a value for a key in dictionaries of a list based on another dictionary?如何根据另一个字典替换列表字典中键的值?
【发布时间】: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


    【解决方案1】:

    您可以将dict.get 与默认参数一起使用:

    lst = [
        {
            "name": "Age",
            "p_value": "<0.001",
            "ks_score": "0.07",
        },
        {
            "name": "peer_LM_Mean_SelfAware",
            "p_value": "<0.001",
            "ks_score": "0.06",
        },
    ]
    
    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 lst:
        d["name"] = col_rename_list.get(d["name"], d["name"])
    
    # pretty print:
    from pprint import pprint
    pprint(lst)
    

    打印:

    [{'ks_score': '0.07', 'name': 'Age, years', 'p_value': '<0.001'},
     {'ks_score': '0.06', 'name': 'Self-Awareness', 'p_value': '<0.001'}]
    

    【讨论】:

    • 这太疯狂了。我就在那儿,但还是错过了。谢谢你给我指路..
    • 为什么使用默认参数等于get中的第一个参数?
    • @igorkf 如果col_rename_list 中不存在d['name'],则返回原始d['name']
    • 如果不存在,你将如何检索 d["name"]?
    • @igorkf 如果col_rename_list 中不存在键d['name'],则.get() 函数返回默认值,在这种情况下为d['name']
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    • 2019-09-04
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 2021-03-11
    • 2015-10-30
    相关资源
    最近更新 更多