【发布时间】:2019-12-26 19:31:38
【问题描述】:
我有这份清单
li=['beststreet','borocd','am_linkid3','bestfrom','bestto','boro','bestborost','sa18','resurf18','allpaving','nocstart','nocend','sa19','resurf19','addedbyrrm','rmmweekly']
我正在遍历 shp,它是来自 fiona 模块 fiona.readthedocs.io/en/latest/manual.html 的有序字典
无需输入以上所有列的示例代码:
for r in shp:
sql_qry='''insert into table (beststreet,borocd) values(%s,%s)'''
values=[r['properties']['beststreet'],r['properties']['borocd']]
cur.execute(sql_qry,values)
如果我对列进行硬编码,此方法将起作用。
问题
我正在创建一个类方法,其中 shp 可以包含任何数量和任何列名。所以我需要弄清楚的是如何构造一个合适的列表来传递给 SQL 查询。
r['properties'] 将始终在开头访问每个字段
所以理想情况下,我想做这样的事情:
values= ["r['properties']["+"'"+l+"'"+"]" for l in li]
打印出来
["r['properties']['beststreet']", "r['properties']['borocd']", "r['properties']['am_linkid3']", "r['properties']['bestfrom']", "r['properties']['bestto']", "r['properties']['boro']", "r['properties']['bestborost']", "r['properties']['sa18']", "r['properties']['resurf18']", "r['properties']['allpaving']", "r['properties']['nocstart']", "r['properties']['nocend']", "r['properties']['sa19']", "r['properties']['resurf19']", "r['properties']['addedbyrrm']", "r['properties']['rmmweekly']"]
这是无效的,但我觉得我很接近。我正在使用python2.7 通过psycopg2 访问postgre 实例。
OrderedDict 示例
shp={'properties': OrderedDict([(u'BestStreet', u'blah AV'), (u'BoroCD', 503L), (u'AM_LINKID3', 106881.0), (u'BestFrom', u'doubt it TER'), (u'BestTo', u'blah AV DEAD END'), (u'Boro', u'SI'), (u'BestBoroSt', u'SI - nuu AV'), (u'SA18', None), (u'resurf18', u'2019'), (u'AllPaving', None), (u'NOCstart', None), (u'NOCend', None), (u'SA19', u'S2305'), (u'resurf19', u'YES'), (u'addedbyRRM', None), (u'RMMweekly', None)])}
【问题讨论】:
-
你正在为什么数据库编写 sql?也许可以使用更好的方法。
-
postgres,使用 psycopg2
-
你使用的是标准的python json模块函数吗?
-
不,我相信 shp 是来自 fiona 模块 fiona.readthedocs.io/en/latest/manual.html 的有序字典,我将使用此信息更新我的问题
-
我猜想将它包裹在
eval周围应该可以工作。[eval("r['properties']["+"'"+l+"'"+"]") for l in li]
标签: python json postgresql python-2.7 psycopg2