In ECMAScript 6, I can do something like this ...
var id = 1;
var name = 'John Doe';
var email = '[email protected]';
var record = { id, name, email };
... as a shorthand for this:
var id = 1;
var name = 'John Doe';
var email = '[email protected]';
var record = { 'id': id, 'name': name, 'email': email };
Is there any similar feature in Python?
In ECMAScript 6, I can do something like this ...
var id = 1;
var name = 'John Doe';
var email = '[email protected]';
var record = { id, name, email };
... as a shorthand for this:
var id = 1;
var name = 'John Doe';
var email = '[email protected]';
var record = { 'id': id, 'name': name, 'email': email };
Is there any similar feature in Python?
Share Improve this question edited Feb 25, 2015 at 15:28 thefourtheye 239k53 gold badges465 silver badges500 bronze badges asked Feb 25, 2015 at 15:26 jawns317jawns317 1,7462 gold badges17 silver badges26 bronze badges 2 |4 Answers
Reset to default 11No, 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))
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'}
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.
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.
{ id, name, email }
is a set-literal in Python. – Ashwini Chaudhary Commented Feb 25, 2015 at 15:28