Search code examples
pythonpython-3.xordereddictionary

How do I extract specific values from an OrderedDict?


I like to extract specific keys and store them onto a list. So far, I am able to read from MariaDB and store the rows as a dictionary (I prefer to have the output as 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)

This produces the output:

[
    {
        "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",
    },
]

I like to extract all occurrences of f. I have tried:

for key, value in d.items():
    print(value)

This outputs:

4153
NO_EFFECT
none
Medium
1
No Remarks

4154
SIGNIFICANT
none
Low
1
Test Message

What I prefer is to only extract f so that the output is like [No Remarks, Test Message] (I assume the sequence is maintained). Can someone please assist how I can achieve or where to look?

Thank you


Solution

  • for obj in objects_list:
        print(obj['f'])
    

    OrderedDict keeps the order of keys (a b c ...). The order in this output comes from the order in objects_list.

    To get it on an output list:

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