Issue
So I used SQL to try to describe a table and got a weird output because my function returns a list so I have this weird format that I want to make into a list of dictionaries. But not sure how I would go about it. And was wondering if someone could point me in the right direction. So here is the list I have
[['Field', 'Type', 'Null', 'Key', 'Default', 'Extra'],
(('_id', 'bigint(20) unsigned', 'NO', 'PRI', None, ''),
('_load_dt', 'date', 'NO', '', None, ''),
('_load_dt_time', 'timestamp', 'YES', 'MUL', 'current_timestamp()', ''),
('_data_hash', 'char(160)', 'YES', 'UNI', None, ''),
('_host', 'char(200)', 'YES', '', None, ''),
('_port', 'int(6)', 'YES', '', None, ''),
('_schema', 'char(200)', 'YES', '', None, ''),
('_deleted', 'tinyint(1)', 'YES', '', '0', ''),
('acct_id', 'varchar(200)', 'NO', 'MUL', None, ''),
('account_title', 'varchar(200)', 'NO', 'MUL', None, ''),
('signup_date', 'varchar(200)', 'NO', 'MUL', None, ''),
('admin_email', 'varchar(200)', 'NO', 'MUL', None, ''))]
I want to the end result to look something like this
[{Field:_id, Type:bigint(20) unsigned, Null:No, Key:PRI, Extra:None}, {Field:_load_dt, Type:date, NULL:No, Key:'', Default:None, Extra:''}, .....]
I'm not sure where to begin, maybe have two loops one that creates the keys by looping through just the first bracket and then another loop that loops through each position in parentheses to get the value for each of those keys?
Solution
Try this:
# This is the info you provided in the original question:
data = [['Field', 'Type', 'Null', 'Key', 'Default', 'Extra'],
(('_id', 'bigint(20) unsigned', 'NO', 'PRI', None, ''),
('_load_dt', 'date', 'NO', '', None, ''),
('_load_dt_time', 'timestamp', 'YES', 'MUL', 'current_timestamp()', ''),
('_data_hash', 'char(160)', 'YES', 'UNI', None, ''),
('_host', 'char(200)', 'YES', '', None, ''),
('_port', 'int(6)', 'YES', '', None, ''),
('_schema', 'char(200)', 'YES', '', None, ''),
('_deleted', 'tinyint(1)', 'YES', '', '0', ''),
('acct_id', 'varchar(200)', 'NO', 'MUL', None, ''),
('account_title', 'varchar(200)', 'NO', 'MUL', None, ''),
('signup_date', 'varchar(200)', 'NO', 'MUL', None, ''),
('admin_email', 'varchar(200)', 'NO', 'MUL', None, ''))]
# Separate the column definitions and the items themselves:
(cols, items) = data
# Use a list comprehension to create a new list that looks the way you expect:
result = [dict(zip(cols, item)) for item in items]
# Done
print(result)
For more info, check out:
Answered By - Donut
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.