The idiomatic way to unpack a dictionary is to use the double star operator **
.
To use it with flask-sqlalchemy
:
class Employee(db.Model)
id = db.Column(...)
firstname = db.Column(...)
lastname = db.Column(...)
employee_data = {'firstname':'John','lastname':'Smith'}
employee = Employee(**employee_data)
db.session.add(employee)
db.session.commit()
Be aware that the keys in the dictionary have to match the attribute names of the class. Unpacking in this manner is the same as:
employee = Employee(firstname='John', lastname='Smith')
You can also do this with a list if you define an __init__
(or other method) with positional arguments however you only use a single star:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
employee_data = ['John', 'Smith']
employee = Employee(*employee_data)
...
Note here the order of the values is what's important.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…