有没有一种干净的方法可以从 psycopg2
DictRow
对象中删除一个项目(包括它的值和索引)?
我正在使用 psycopg2
与两个不同的 postgresql 数据库进行交互。我想将记录作为 DictRow 从一个数据库复制到另一个数据库 - 并且我想在插入记录之前从记录中删除几个字段。
例如,如果我有一个名为 row
的 DictRow:
>>> print row
[12, '2015-12-31', 'kefir sriracha put a bird on it']
>>> print row.keys()
['id', 'created_at', 'output_example']
使用 row.pop(INDEX)
更改列表的索引,因此存储在 row._index
属性中的键不再正确!
>>> row.pop(0)
12
>>> print row
['2015-12-31', 'kefir sriracha put a bird on it']
>>> print row.keys()
['id', 'created_at', 'output_example']
>>> print row['id']
'2015-12-31' # GAAAAA!!!
您不能使用 del row['id']
:TypeError
。我认为这是因为底层对象是一个 list
并且需要一个整数索引。
我目前的解决方法是做这样的事情,这看起来并不优雅:
fields = [f for f in row.keys() if f != 'id']
values = [v for k, v in row.iteritems() if k != 'id']
对于从 DictRow 中删除项目的更直接的方法有什么建议吗?
最佳答案
cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
query = """select 1 as one, 2 as two"""
cursor.execute(query)
rs = cursor.fetchall()
d = rs[0]
print d
del(d['one'])
print d
输出:
{'two': 2, 'one': 1}
{'two': 2}
关于python - 从 DictRow 中删除一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34550843/