【发布时间】:2020-07-17 18:23:07
【问题描述】:
我喜欢提取特定的键并将它们存储到一个列表中。到目前为止,我能够从 MariaDB 读取数据并将行存储为字典(我更喜欢将输出作为 JSON):
import pymysql
import simplejson as json
import collections
import credentials_global
conn = pymysql.connect(
host=credentials_global.mariadb_dev_ip_address,
user=credentials_global.mariadb_dev_username,
password=credentials_global.mariadb_dev_password,
port=credentials_global.mariadb_dev_port,
database=credentials_global.mariadb_dev_db_ticketing,
)
cursor = conn.cursor()
cursor.execute("select a, b, c, d, e, f from master.orders where c = 215")
rows = cursor.fetchall()
objects_list = []
for row in rows:
d = collections.OrderedDict()
d["a"] = row[0]
d["b"] = row[1]
d["c"] = row[2]
d["d"] = row[3]
d["e"] = row[4]
d["f"] = row[5]
objects_list.append(d)
j = json.dumps(objects_list)
print(j)
这会产生输出:
[
{
"a": 4153,
"b": "NO_EFFECT",
"c": "none",
"d": "Medium",
"e": 1,
"f": "No Remarks",
},
{
"a": 4154,
"b": "SIGNIFICANT",
"c": "none",
"d": "Low",
"e": 1,
"f": "Test Message",
},
]
我喜欢提取所有出现的f。我试过了:
for key, value in d.items():
print(value)
这个输出:
4153
NO_EFFECT
none
Medium
1
No Remarks
4154
SIGNIFICANT
none
Low
1
Test Message
我更喜欢只提取f,以便输出类似于[No Remarks, Test Message](我假设保持顺序)。有人可以帮助我如何实现或在哪里寻找?
谢谢
【问题讨论】:
标签: python python-3.x ordereddictionary