[英]update set values with dictionary with multiple values per key
我有一个如下所示的 sqldb 表
| tag | unit | description|
|:---- |:------:| -----:|
| 1a | % | mass flow |
| 2a | * | head flow |
我想用下面的字典将值更新到表中
{'1a': ['%', 'head flow'], '2a': ['%', 'head flow'], '3a': ['%', 'mass flow']}
我想像这样使用 for 循环更新值
for tag in tag_list:
key=tag
unit_value=(dictionary[tag][0] if tag in source_dictionary else None)
desc_value=(dictionary[tag][1] if tag in source_dictionary else None)
cursor.execute("UPDATE tag_metadata SET unit= ? , description = ? where tag_name= ?",unit_value,desc_value,key)
cursor.commit()
我只是想知道它是否会起作用..如果没有,我怎样才能使它起作用?
谢谢你
这是可能的。 只需稍微修改您的字典。 如果您有问题,请告诉我
字典
d={'1a': "%, head flow", '2a': "%, head flow", '3a': "%, mass flow"}
#创建ma表达式
m_expr1 = create_map([lit(x) for x in chain(*d.items())])
Map 值并将字符串拆分为列表
df.withColumn('tag1', split(m_expr1[lower(df['tag'])],'\,')).show()
你可以这样做:
for tag in d:
cursor.execute("UPDATE tag_metadata SET unit = ? , description = ? where tag_name = ?",
d[tag][0], d[tag][1], tag)
cursor.commit()
这将使用您描述的值更新d
中提到的所有记录。
或者,如果您必须处理更多值,则可以使用以下变体:
for tag in d:
cursor.execute("UPDATE tag_metadata SET unit = ? , description = ? where tag_name = ?",
*(d[tag]+[tag]))
这会将tag
作为最后一个值添加到该标记的d
中已经存在的值列表中,然后使用解包运算符将它们传播到对.execute()
的调用中。
但是,在后一种情况下,您必须确保字典中字段的顺序与它们在查询中出现的顺序相匹配,而在前一种情况下,您可以通过索引来控制它。
在任何一种情况下,您都可以按照您的定义使用d
。
你可以这样做使用 Dataframe 和 rdd
>>> df.show()
+---+----+-----------+
|tag|unit|description|
+---+----+-----------+
| 1a| %| mass flow|
| 2a| *| head flow|
+---+----+-----------+
>>> df.rdd.map(lambda x:(x[0], list(x[0:]))).take(10)
[('1a', ['1a', '%', 'mass flow']), ('2a', ['2a', '*', 'head flow'])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.