I'm using glom project.
Is there a way to convert [{"id": 1, "name": "foo"}, {"id": 2, "name": "bar"}]
to {1: "foo", 2: "bar"}
?
The method to merge multiple dictionaries is simple: Create a new, empty dictionary. Go over each dictionary in the list of dictionaries. Update the new dictionary with the values in the current dictionary.
New glom
version (19.2.0) allows to use Merge
to merge two dicts.
from glom import glom, T, Merge
target = [{"id": 1, "name": "foo"}, {"id": 2, "name": "bar"}]
spec = Merge([{T["id"]: T["name"]}])
glom(target, spec)
# {1: 'foo', 2: 'bar'}
Docs: https://glom.readthedocs.io/en/latest/api.html?highlight=merge#glom.Merge
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With