python - 从 DictRow 中删除一个项目

标签 python postgresql psycopg2

有没有一种干净的方法可以从 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 中删除项目的更直接的方法有什么建议吗?

最佳答案

使用 RealDictCursor

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/

相关文章:

python - 按键连接数据框 - 重复数据作为新列

regex - 数字的 Postgresql 模式匹配字符串列

连续 ID block 上的 PostgresQL 窗口函数

python - Psycopg2 单引号异常

python - PostgreSQL 类型错误 : not all arguments converted during string formatting

python - 使用 matplotlib.pyplot 在 python 中绘图的线条样式功能

python - 基于部分startswith匹配合并两个数据帧

python - F() 表达式和从 F() 表达式创建的 timedelta 的总和

r - 使用 R 在 postgres 中设置模式名称

python - PostgreSQL 关系不存在 (Python)