Sandy Sandy - 3 months ago 8
Python Question

Sorting all the sub Dictionary using values of one of the sub dictionary

I have data structure like the below and would like to sort the
all the sub dictionaries to be sorted based on the values of the 'order' column.

Input:

to_sort = [
('Fruits',
{
'size': {1:[4, 2, 7,9]},
'name': {1:['Orange', 'Apple', 'Kiwi', 'Mango']},
'color': {1:['Orange', 'Red', 'Brown','Green']},
'order': {1:[2, 1, 4,3]}
}
)
]


output:

[
('Fruits',
{
'size': {1:[2, 4, 9, 7]},
'name': {1:['Apple', 'Orange', 'Mango', 'Kiwi']},
'color':{1:['Red', 'Orange', 'Green', 'Brown']},
'order':{1:[1, 2, 3, 4]}
}
)
]


I tried using the lambda

sort = to_sort[1]
print(sorted(sort.items(), key=lambda i: i['order'].values()))


i am getting "tuple indices must be integers or slices, not str" error

Answer

Assuming you are okay with modifying your data structure as mentioned in the comments, this will work for you. This is adapted from this other question: Sorting list based on values from another list?

to_sort = [('Fruits', {
    'size': [4, 2, 7,9],
    'name': ['Orange', 'Apple', 'Kiwi', 'Mango'],
    'color': ['Orange', 'Red', 'Brown','Green'],
    'order': [2, 1, 4,3]
    })
]

postsort = []
for category, catdata in to_sort:
    sorteddata = {}
    for name, namedata in catdata.iteritems():
        sorteddata[name] = [x for (y,x) in sorted(zip(catdata['order'], namedata))]
    postsort.append((category, sorteddata))
print postsort

Which results in:

[(
    'Fruits',
    {
        'color': ['Red', 'Orange', 'Green', 'Brown'],
        'size': [2, 4, 9, 7],
        'order': [1, 2, 3, 4],
        'name': ['Apple', 'Orange', 'Mango', 'Kiwi']
    }
)]

This could be modified to work with your existing data structure, but I would recommend making the change if that is possible.