Reputation: 23
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
Upvotes: 1
Views: 2797
Reputation: 2195
Assuming the output received is over a list:
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"}]
We can perform 2 ways, with one iterating normally not assuming over key order, another one with the order.
f_list = list()
for val in ex:
for k, v in val.items():
if k == "f":
f_list.append(v)
print(f_list)
Output:
['No Remarks', 'Test Message']
f_list = list()
for val in ex:
f_list.append(val["f"])
print(f_list)
Output:
['No Remarks', 'Test Message']
Upvotes: 0
Reputation: 119
I think the answer your looking for is
for key, value in d.items():
print(value[0]['f'])
first element 0 in the list, and within that list, the element f in the dictionary.
Upvotes: 0
Reputation: 364
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 ]
Upvotes: 2