2

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!

P. Solar
  • 339
  • 3
  • 10
  • 1
    What is `vars`? Is it a `list` of `dict`s? Post a sample input and your expected output. – Selcuk Jan 10 '23 at 10:10
  • 1
    You can probably use the `zip()` function and combine with a dictionary comprehension. `zip()` function: https://www.programiz.com/python-programming/methods/built-in/zip ; dict comprehension: https://stackoverflow.com/questions/14507591/python-dictionary-comprehension – Haroldo_OK Jan 10 '23 at 10:11

1 Answers1

1

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]
Jamiu S.
  • 5,257
  • 5
  • 12
  • 34