20

In ECMAScript 6, I can do something like this ...

var id = 1;
var name = 'John Doe';
var email = 'email@example.com';
var record = { id, name, email };

... as a shorthand for this:

var id = 1;
var name = 'John Doe';
var email = 'email@example.com';
var record = { 'id': id, 'name': name, 'email': email };

Is there any similar feature in Python?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
jawns317
  • 1,726
  • 2
  • 17
  • 26

4 Answers4

10

No, but you can achieve identical thing doing this

record = {i: locals()[i] for i in ('id', 'name', 'email')}

(credits to Python variables as keys to dict)

Your example, typed in directly in python is same as set and is not a dictionary

{id, name, email} == set((id, name, email))
Ski
  • 14,197
  • 3
  • 54
  • 64
2

No, there is no similar shorthand in Python. It would even introduce an ambiguity with set literals, which have that exact syntax:

>>> foo = 'foo'
>>> bar = 'bar'
>>> {foo, bar}
set(['foo', 'bar'])
>>> {'foo': foo, 'bar': bar}
{'foo': 'foo', 'bar': 'bar'}
Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
2

You can't easily use object literal shorthand because of set literals, and locals() is a little unsafe.

I wrote a hacky gist a couple of years back that creates a d function that you can use, a la

record = d(id, name, email, other=stuff)

Going to see if I can package it a bit more nicely.

AlexeyMK
  • 6,245
  • 9
  • 36
  • 41
0

Yes, you can get this quite nicely with a dark magic library called sorcery which offers dict_of:

x = dict_of(foo, bar)
# same as:
y = {"foo": foo, "bar": bar}

Note that you can also unpack like ES6:

foo, bar = unpack_keys(x)
# same as:
foo = x['foo']
bar = x['bar']

This may be confusing to experienced Pythonistas, and is probably not a wise choice for performance-sensitive codepaths.

rattray
  • 5,174
  • 1
  • 33
  • 27