[英]Creating a dynamic key within list comprehension
I am using sqlalchemy(core) to extract primary key column(s) from an alchemy table.我正在使用 sqlalchemy(core) 从炼金术表中提取主键列。 So in essence I do this initially:所以本质上我最初是这样做的:
coupon_tbl = db.Table( "issued_coupon", metadata, autoload=True, autoload_with=engine, schema="pricer" coupon_tbl = db.Table("issued_coupon", metadata, autoload=True, autoload_with=engine, schema="pricer"
Now in order to extract the primary key columns, I iterate over the corresponding object like this:现在为了提取主键列,我像这样遍历相应的 object:
pk_tuple = []
for x in coupon_tbl.primary_key.columns._all_columns:
pk_tuple.append(x.name)
pk_tuple = tuple(pk_tuple)
Now what I would like to do is to create a dictionary that has the a tuple of keys as the dictionary key like so:现在我想做的是创建一个字典,其中包含一个键元组作为字典键,如下所示:
for rec in batchrecordlist:对于批处理记录列表中的记录:
batchrecorddict[(rec["user_id"], rec["timestamp"])] = rec
But how do I do this dynamically?但是我如何动态地做到这一点? I want something like this:我想要这样的东西:
batchrecorddict["expansion of tuple perhaps?"] = rec. batchrecorddict["可能是元组的扩展?"] = rec. So if there were in fact 3 columns to the primary key, then the assignment would look like this:因此,如果主键实际上有 3 列,那么分配将如下所示:
batchrecorddict[(rec["user_id"], rec["timestamp"], rec["3rd column of key])] = rec etc... batchrecorddict[(rec["user_id"], rec["timestamp"], rec["3rd column of key])] = rec 等...
Can this be done?这可以做到吗?
I figured it out, pretty simply actually:我想通了,实际上很简单:
Create this function:创建这个 function:
def renderPKtuple(rec, pkcolumn): tmplist = [] def renderPKtuple(rec, pkcolumn): tmplist = []
for x in pkcolumn:
tmplist.append(rec[x])
return tuple(tmplist)
And then in the loop call it this way:然后在循环中这样调用它:
for rec in batchrecordlist:对于批处理记录列表中的记录:
batchrecorddict[renderPKtuple(rec, pk_tuple)] = rec
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.