如何从OrderedDict中提取特定值?

问题描述 投票:1回答:3

我喜欢提取特定的密钥并将其存储到列表中。到目前为止,我已经能够从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
3个回答
1
投票
for obj in objects_list:
    print(obj['f'])

OrderedDict保留键的顺序(a b c ...)。此输出中的顺序来自objects_list中的顺序。

要在输出列表上获取它:

only_f_fields = [ obj['f'] for obj in objects_list ]

0
投票

我认为您寻找的答案是

for key, value in d.items():    
    print(value[0]['f'])

列表中的第一个元素0,在该列表中,字典中的元素f。


0
投票

假设接收到的输出在列表中:ex = [{"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"}]

我们可以执行2种方法,其中一种通常不假定按键顺序重复进行迭代,另一种可以按顺序进行迭代。

通常进行迭代和检查

f_list = list()
for val in ex:
    for k, v in val.items():
        if k == "f":
           f_list.append(v)

print(f_list)
输出:

['No Remarks', 'Test Message']

假设键顺序的有序字典,一个更快的键

f_list = list()
for val in ex:
    f_list.append(val["f"])
print(f_list)
输出:

['No Remarks', 'Test Message']

© www.soinside.com 2019 - 2024. All rights reserved.