仅更新python中dicts列表中某些键的值

时间:2016-04-08 11:45:53

标签: list python-2.7 dictionary

我有一个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_inpatient is_diabetic 的值,如果0为否,且1为是。

我开始首先检查dict中键的存在,如下所示:

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

但我不确定进一步实现这一目标的好方法是什么?

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分:0)

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

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"

请注意,如果字典中没有键(0),k就是默认值。

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