如何将psycopg2返回的元组列表转换为字典并格式化数据
PostgreSQL数据处理:将元组列表转为字典并格式化增长率
问题场景
我有一个名为stockdata的PostgreSQL表,存储约250家公司的财务数据,表结构如下:
Company q4_2022_revenue q3_2022_revenue CPI Card 126436000 124577000 Zuora 103041000 101072000 …
用Python的psycopg2导入数据的代码:
import psycopg2 conn = psycopg2.connect('dbname=postgres user=postgres password=…') cur = conn.cursor() cur.execute('SELECT company, (q4_2022_revenue-q3_2022_revenue)/CAST(q3_2022_revenue AS float) AS revenue_growth FROM stockdata ORDER BY revenue_growth DESC LIMIT 25;') records = cur.fetchall() print(records)
执行后得到元组组成的列表:
[('Alico', 9.269641125121241),('Arrowhead Pharmaceuticals', 1.7705869324473975),…]
需求:
- 将公司名作为字典键、增长率作为值,生成可变字典
- 把
9.2696这类格式的增长率转为保留两位小数的百分比(如926.96%)
之前尝试代码:
list((x,y) for x,y in records)
调用records[x]时出现name 'x' is not defined错误。
解决方案
1. 一步完成字典转换与格式化
用字典推导式直接实现转换和格式修改:
growth_dict = { company: f"{growth * 100:.2f}%" for company, growth in records }
- 遍历
records中的每个元组,将公司名作为键 growth * 100转换为百分比基数,:.2f保留两位小数,拼接%符号得到最终格式- 生成的
growth_dict是可变字典,可直接修改键值对
2. 分步处理(保留原始数据)
如果需要保留原始增长率数值,可分两步操作:
# 先转为存原始数值的字典 raw_growth_dict = dict(records) # 格式化增长率并生成新字典 formatted_growth_dict = {} for company, growth in raw_growth_dict.items(): formatted_value = f"{growth * 100:.2f}%" formatted_growth_dict[company] = formatted_value
3. 错误原因说明
之前的list((x,y) for x,y in records)只是重新生成了原列表,并没有创建字典。records[x]报错是因为x是推导式内的临时变量,外部未定义;且records是列表,只能用索引(如records[0])访问,不能用公司名作为键。
结果示例
执行后growth_dict的内容类似:
{'Alico': '926.96%', 'Arrowhead Pharmaceuticals': '177.06%', ...}
内容的提问来源于stack exchange,提问作者user19891327
相关产品推荐
相关产品推荐

