I have a list of dictionaries (actually, a list of objects containing dictionaries) like this, representing a table:
rows = [
{ '11': 14, '12': 0, '13': 0, '14': 20 },
{ '13': 8 },
{ '11': 7, },
{ '11': 2, '14': 2 },
{ '12': 2, '13': 2 },
{ '11': 3, '14': 3 },
{ '11': 1, '14': 1 },
{ '13': 5 },
{ '11': 8, },
{ '11': 0, '14': 0 },
{ '11': 9, },
{ '14': 10 },
{ '13': 19 },
{ '14': 12 },
{ '13': 15 },
{ '12': 3, '13': 3 }
]
I want to sort them by each column in the table like this:
[
{ '11': 0, '14': 0 },
{ '11': 1, '14': 1 },
{ '11': 2, '14': 2 },
{ '11': 3, '14': 3 },
{ '14': 10 },
{ '14': 12 },
{ '11': 7 },
{ '11': 8 },
{ '11': 9 },
{ '11': 14, '12': 0, '13': 0, '14': 20 },
{ '12': 2, '13': 2 },
{ '12': 3, '13': 3 },
{ '13': 5 },
{ '13': 8 },
{ '13': 15 },
{ '13': 19 }
]
There are a few possible 'correct' orders, but that's one of them.
I've seen and tried various solutions for this sort of thing, but they all seem to involve placing None
at the beginning or end of the list, which I don't want. For example:
rows.sort(key=lambda r: [r.get(c, 0) for c in ['11', '12', '13', '14']])
There are certain items that can't be compared (because they have no keys in common), but a comparison function can't return 'I don't know', can it?
I'm using Python 3.5, but it would be nice to stay compatible with 2.7 and 3.4.