Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to merge a list of dicts into a single dict using glom library? [duplicate]

Tags:

python

glom

I'm using glom project.

Is there a way to convert [{"id": 1, "name": "foo"}, {"id": 2, "name": "bar"}] to {1: "foo", 2: "bar"}?

like image 405
proofit404 Avatar asked Feb 19 '19 08:02

proofit404


People also ask

How do I merge a list of dictionaries?

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.


1 Answers

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

like image 63
sobolevn Avatar answered Sep 25 '22 16:09

sobolevn