DEV Community

loading...

Discussion on: What's your favorite Python idiom?

Collapse
bctnry profile image
Sebastian Higgins

Dict comprehension:

{i: x for i, x in enumerate([1, 2, 3])}
# returns {0: 1, 1: 2, 2: 3}

if you happen to have a bunch of object with some kind of an id field (like I do) you can do this:

{x['id']: x for x in [{'id': 3}, {'id': 4}, {'id': 5}]}
# returns {3: {'id': 3}, 4: {'id': 4}, 5: {'id': 5}}

which is sometimes pretty neat I think.