Last active
March 19, 2018 18:04
-
-
Save clayadavis/3b61706ba99a88575f0e83de5025a3ab to your computer and use it in GitHub Desktop.
Flatten a botometer response
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import namedtuple | |
DataRow = namedtuple('DataRow', ['header', 'data']) | |
def flatten_botometer_result(result): | |
''' | |
Flattens a botometer response object. | |
Parameters: | |
result: A botometer result object | |
Returns a DataRow, a namedtuple containing the header and the data | |
header: list of names for the data columns, suitable for use as a csv header | |
data: list containing flattened data from the response object, i.e. a csv row | |
Usage (single account): | |
result = bom.check_account('@clayadavis') | |
header, data = flatten_botometer_response(result) | |
<do something with the data and/or header here> | |
Usage (several accounts): | |
for screen_name, result in bom.check_accounts_in(accounts): | |
header, data = flatten_botometer_response(result) | |
<do something with the data and/or header here> | |
''' | |
header = [] | |
data = [] | |
for top_level in ['user', 'scores', 'categories']: | |
for bottom_level in sorted(result[top_level]): | |
key = '%s__%s' % (top_level, bottom_level) | |
header.append(key) | |
data.append(result[top_level][bottom_level]) | |
return DataRow(header=header, data=data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do note that the
header, data
output can be easily transformed into aOrderedDict
ordict
record:The above snippet works with a
dict
instead ofOrderedDict
.