Reputation: 59
So say I have some data... say:
Dictionary = {'stats': stats, 'lines': arr}
Where 'stats' a simple string, and arr is a list of lists:
[['A', '#ccebf6', 0, 365, 240, 0],
['D', '#ccebf6', 0, 25, 250, 0],
['A', '#96dcd8', 0, 65, 230, 1],
['T', '#96dcd8', 0, 25, 230, 1],
['E', '#ccebf6', 0, 370, 240, 2],
['B', '#ccebf6', 0, 25, 250, 3]]
and say I use
json_string = json.dumps(Dictionary)
To get a lovely JSON:
'{"stats": {"somestuff..."'"lines": [["some list stuff..]][[..]]"
But in arr, say in last element, I have a an Item I wish to group the "lines" by, call it 'line:' eg
[['A', '#ccebf6', 0, 365, 240, 0],
['D', '#ccebf6', 0, 25, 250, 0],
['A', '#96dcd8', 0, 65, 230, 1],
['T', '#96dcd8', 0, 25, 230, 1],
['E', '#ccebf6', 0, 370, 240, 2],
['B', '#ccebf6', 0, 25, 250, 3]]
And I wish to order my lists by that last element, to have them in JSON form:
{'lines'[{'val':0, [['A', '#ccebf6', 0, 365, 240, 0],
['D', '#ccebf6', 0, 25, 250, 0]],
'val':1, [['A', '#96dcd8', 0, 65, 230, 1],
['T', '#96dcd8', 0, 25, 230, 1]],
'val':2, [['E', '#ccebf6', 0, 370, 240, 2]],
'val'3, [['B', '#ccebf6', 0, 25, 250, 3]]}]}
Which obviously needs an appropriate dictionary form.
I understand this may not be explained well but let me know if clarification is necessary.
I attempted to sort them using a lambda expression, for that final value in arr. But I do not know how to create them in that format for the dictionary.
Upvotes: 0
Views: 45
Reputation:
You can use a dict to group your items.
lines = {}
for row in arr:
key = row[-1]
lines.setdefault(key, []).append(row)
Result:
>>> lines
{0: [['A', '#ccebf6', 0, 365, 240, 0], ['D', '#ccebf6', 0, 25, 250, 0]],
1: [['A', '#96dcd8', 0, 65, 230, 1], ['T', '#96dcd8', 0, 25, 230, 1]],
2: [['E', '#ccebf6', 0, 370, 240, 2]],
3: [['B', '#ccebf6', 0, 25, 250, 3]]}
Upvotes: 1