Amistad
Amistad

Reputation: 7410

Updating values for only certain keys in a list of dicts in python

I have a Python list of dicts as follows:

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"
}
]

What I would want is to change the values of only the keys is_inpatient and is_diabetic if 0 to No and if 1 to Yes.

I started with first checking the existence of the keys in the dict as follows :

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

But i am not sure what would be a nice way of accomplishing this further ?

Upvotes: 1

Views: 1103

Answers (2)

jDo
jDo

Reputation: 4010

One line (and some list comprehension abuse):

[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]

Two lines (but no abuse):

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"))

More lines:

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"

Even more lines:

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"

Upvotes: 2

nickpapior
nickpapior

Reputation: 782

Here you may use the default parameter of retrieving a value from a dictionary, in this way you reduce complexity:

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"

remark that 0 is then the default value if the key (k) is not present in the dictionary.

You may additionally change the above code to handle arbitrary is_* keys by extending the functionality further.

Upvotes: 0

Related Questions