Given a list of dictionaries:
the_list = [{k1:v1,k2:v2}, {k1:v3, k3:v4}, {k1:v5,k2:v6},{k3:v7}]
How can I update the value for k2
based on a condition based on the value of k1
?
I would come up with this solution but it doesn't feel Pythonic. Better solutions anyone?
for item in the_list:
if set([k1,k2]) <= item.keys():
#cond evaluates to True or False
if cond(item[k1]):
item.update({k2:newvalue})
Maybe this can be done better with a map or lambda expression?
This is the simplest code I came up with to perform the same operation:
my_list = [{k1:v1,k2:v2}, {k1:v3, k3:v4}, {k1:v5,k2:v6},{k3:v7}]
for my_dict in my_list:
if all (k in my_dict for k in ("k1", "k2")):
if cond(my_dict[k1]):
my_dict[k2] = newvalue # possibly pre-determined
Depending on the way cond
evaluates the value of k1
and/or newvalue
is generated, the code might be further more "Pythonized".
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments