I am updating the key names of a list of dictionaries in this way:
def update_keys(vars: list) -> None:
keys = ["A", "V", "C"]
for v in vars:
for key in keys:
if key in v:
v[key.lower()] = v.pop(key)
Is there any pythonic way to do the key loop/update in one single line? Thank you in advance!
CodePudding user response:
You can use map
with lambda
to accomplish that, vars[:]
will be updating the original list vars
.
def update_keys(vars: list) -> None:
keys = ["A", "V", "C"]
vars[:] = map(lambda v: {k if k not in keys else k.lower(): v[k] for k in v}, vars)
List comprehension with the use of update
can also accomplish same result.
def update_keys(vars: list) -> None:
keys = ["A", "V", "C"]
[v.update({key.lower(): v.pop(key) for key in keys if key in v}) for v in vars]