qarthandso
qarthandso

Reputation: 2188

ES6 Computed Property Names in Python

I'm trying to find an equivalent ES6 feature in Python.

In JS, I have something like this:

let obj = {['composed' + objKey()]: true}

I want do be able to compose a dictionary key in a dict constructor in Python as well, something like:

MyClass.render(storyboard=dict([getAuthor()]=self.authorStoryData()))

[getAuthor()] should result in a dictionary key of the return value of that function. Or if it's variable, it's value, etc...

Is there anyway to do this in Python?

I've tried doing dict=('%s' % (variable,)=self.content but that threw errors.

Upvotes: 5

Views: 1522

Answers (1)

poke
poke

Reputation: 387825

Just like you use an object literal in JavaScript, you should use a dictionary literal in Python for this. This would be the exact equivalent in Python:

def objKey():
   return 'foo'

obj = {
    'composed' + objKey(): True
}

print(obj['composedfoo']) # True

Or in your actual case:

MyClass.render(storyboard={ getAuthor(): self.authorStoryData() })

As Jon highlights on the comments, the big difference between a JavaScript object literal and a Python dict literal is that Python’s behavior for the keys is basically JavaScript’s behavior with [] by default.

So to translate a { [expr]: value } in JavaScript, you would write { expr: value } in Python. But when you just write { key: value } in JavaScript, you have to understand it’s essentially a { ['key']: value } which makes it equivalent to { 'key': value } in Python.

The reason why you need a string literal for string keys is simply because Python dictionaries can have almost arbitrary key objects and are not limited to string keys as JavaScript objects are.

Upvotes: 8

Related Questions