Xen_mar
Xen_mar

Reputation: 9702

Transform object into keymap structure?

I'm looking for a quick way to transform an object into a structure like this in Python:

obj = [{"id": "a"}, {"id": "b"}, {"id": "c"}]

Into:

mapobj = {"a": {"id": "a"}, "b": {"id": "b"}, "c": {"id": "c"}}

In javascript we can use losdash's _.mapkeys()for this.

Upvotes: 0

Views: 47

Answers (2)

kol
kol

Reputation: 28698

mapObj = dict(map(lambda dct: (dct["id"], dct), obj))

Here is an online test.

Upvotes: 1

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

mapobj = {dct["id"]: dct for dct in obj}

Upvotes: 5

Related Questions