Sorting Output Of Python File By Location, Increment By Common Id
Solution 1:
If I understand correctly, you have a list of items with a structure like this:
...
{{'data': {'id': 3, 'type': 'location'} ... }
{{'data': {'id': 3, 'type': 'location'} ... }
{{'data': {'id': 4, 'type': 'location'} ... }
...
And you want to count the number of items with each unique combination of id
and type
, and print the results in sorted order?
You could use the general counting dictionary pattern:
counts = dict()
for item in data['data']:
# here I assume the items you are looking for are locations# for it to be a key, it has to be immutable, so make it a tuple
val = item['relationships']['location']['data']
location_tuple = (val['id'], val['type'])
if location_tuple in counts:
counts[location_tuple] += 1else:
counts[location_tuple] = 1# print them out in order, first send to list of tuples and sort
results = counts.items()
results.sort() # will sort on first item, which will be id# results come in like so: ((3, location), 15)for item in results:
print'id:', item[0][0], 'type:', item[0][1], 'count:' item[1]
Basic idea here is that you can use the dictionary to count using tuples as keys of all the distinct things you want to count, and then use items to get it as a list of tuples, which can be sorted. Tuples are sorted by first-element, second-element, and so on, recursively, so take care when building tuples to put your first sort key in the first position, and so on, or you'll have to make adjustments to your sort call. You may have to adjust what I have depending on what you want to extract and print.
Solution 2:
Put data in database (SQLite for example) then "GROUP BY".
Post a Comment for "Sorting Output Of Python File By Location, Increment By Common Id"