5

I'm using glom project.

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

Jeff Hammerbacher
  • 4,226
  • 2
  • 29
  • 36
proofit404
  • 281
  • 1
  • 13
  • 5
    This is not a duplicate. That question is completely different from the one asked here. @ConstantinGuidon – taurus05 Feb 19 '19 at 08:54

1 Answers1

8

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

sobolevn
  • 16,714
  • 6
  • 62
  • 60