【问题标题】:Updating values for only certain keys in a list of dicts in python仅更新python中字典列表中某些键的值
【发布时间】:2016-04-08 11:45:53
【问题描述】:

我有一个 Python 字典列表如下:

result =  
[
{
    "is_inpatient": 0, 
    "fulfillment_time": "100", 
    "total_prescriptions": 56, 
    "total_patients": 999, 
    "mean_refills": "11.0000"
},
{
    "is_diabetic": 0, 
    "fulfillment_time": "9487", 
    "total_prescriptions": 0, 
    "total_patients": 9, 
    "mean_refills": "11.0000"
},
{
    "is_diabetic": 1, 
    "fulfillment_time": "225", 
    "total_prescriptions": 34, 
    "total_patients": 96, 
    "mean_refills": "11.0000"
}
]

我想要的只是将键 is_inpatientis_diabetic 的值更改为 0 为否,如果 1 为是。

我首先检查字典中的键是否存在,如下所示:

for item in result:
    if 'is_diabetic' in item  or 'is_inpatient' in item:

但我不确定进一步完成此任务的好方法是什么?

【问题讨论】:

    标签: list python-2.7 dictionary


    【解决方案1】:

    一行(和一些列表理解滥用):

    [d.update((k, {1:"Yes", 0:"No"}[v]) for k, v in d.iteritems() if v in (1,0) and k in ("is_diabetic", "is_inpatient")) for d in result]
    

    两行(但没有滥用):

    for d in result:
        d.update((k, {1:"Yes", 0:"No"}[v]) for k, v in d.iteritems() if v in (1,0) and k in ("is_diabetic", "is_inpatient"))
    

    更多行:

    to_change = ("is_diabetic", "is_inpatient")
    
    for d in result:
        for k in to_change:
            if k in d:
                if d[k] == 1:
                    d[k] = "Yes"
                else:
                    d[k] = "No"
    

    更多行:

    for d in result:
        if "is_diabetic" in d:
            if d["is_diabetic"] == 1:
                d["is_diabetic"] = "Yes"
            else:
                d["is_diabetic"] = "No"
        if "is_inpatient" in d:
            if d["is_inpatient"] == 1:
                d["is_inpatient"] = "Yes"
            else:
                d["is_diabetic"] = "No"
    

    【讨论】:

    • @Amistad 更新了我的答案
    【解决方案2】:

    这里您可以使用从字典中检索值的默认参数,这样可以降低复杂性:

    to_change = ("is_diabetic", "is_inpatient")
    
    for d in result:
        for k in to_change:
            if d.get(k, 0) == 1:
                d[k] = "Yes"
            else:
                d[k] = "No"
    

    如果字典中不存在键 (k),则注意 0 是默认值。

    您还可以通过进一步扩展功能来更改上述代码以处理任意is_* 键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      • 2021-07-24
      • 2020-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多