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?
A literal in both Python and JavaScript is a value that in the code represents itself, rather than acting as a reference to - or operations upon - other things in the code. Some simple examples include string and numerical literals in both Python and JavaScript ( 1 , "foo bar baz" , 3.1415 and so on).
The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array. Values created with anonymous functions are methods of your object. Simple values are properties.
In ES6, the computed property name is a part of the object literal syntax, and it uses the square bracket notation. When a property name is placed inside the square brackets, the JavaScript engine evaluates it as a string. It means that you can use an expression as a property name.
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With