Skip to content

Instantly share code, notes, and snippets.

@clayadavis
Last active March 19, 2018 18:04
Show Gist options
  • Save clayadavis/3b61706ba99a88575f0e83de5025a3ab to your computer and use it in GitHub Desktop.
Save clayadavis/3b61706ba99a88575f0e83de5025a3ab to your computer and use it in GitHub Desktop.
Flatten a botometer response
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)
@clayadavis
Copy link
Author

clayadavis commented Mar 19, 2018

Do note that the header, data output can be easily transformed into a OrderedDict or dict record:

from collections import OrderedDict

header, data = flatten_botometer_response(result)
record = OrderedDict(zip(header, data))

The above snippet works with a dict instead of OrderedDict.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment