簡體   English   中英

如何根據另一個字典替換列表字典中鍵的值?

[英]How to replace a value for a key in dictionaries of a list based on another dictionary?

以下是數據示例:

[{
  'name': 'Age', 
  'p_value': '<0.001', 
  'ks_score': '0.07', 
}, 
{
  'name': 'peer_LM_Mean_SelfAware', 
  'p_value': '<0.001', 
  'ks_score': '0.06', 
}]

我有超過 16k 的字典,列表中有幾個項目。 我想要做的是從另一個由舊名稱和新名稱組成的字典中替換該字典中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)

這行得通,但是有沒有更好更有效的方法來做到這一點?

您可以將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'}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM