0

In javascript, say we have two local variables name and age, and we want to create an object literal (dictionary) in the form:

let person = {
    name: name,
    age: age
}

This assignment can be shortened to this statement with the same outcome:

let person = {
    name,
    age
}

Is there an equivalent shorthand for this in python? Or do dictionaries have to be written like this?

person = {
    "name": name,
    "age": age
}
ThinkingInBits
  • 10,792
  • 8
  • 57
  • 82

1 Answers1

2

No, there's nothing built-in that does this.

You could define a function that does it, but you'd have to pass it the locals() dictionary so it can access those variables.

def dictvars(l, *names):
    return {name: l[name] if name in l else globals()[name] for name in names}

name = "myname"
def makeperson(age):
    person = dictvars(locals(), "name", "age")
    return person

print(makeperson(20)) # {'name': 'myname', 'age': 20}
Barmar
  • 741,623
  • 53
  • 500
  • 612