I want to sort a list by the number of confirmation small to big. If confirmation is empty, the confirmation number is same as zero. I got the following error. How can fix it?
Before sort
[
{
'id':'1',
'confirmation':'20',
},
{
'id':'2',
'confirmation':'10',
},
{
'id':'3'
}
]
After sort
[
{
'id':'3'
},
{
'id':'2',
'confirmation':'10',
},
{
'id':'1',
'confirmation':'20',
}
]
Test
$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31)
>>> dict1 = {"id":1, "confirmation":20}
>>> dict2 = {"id":2, "confirmation":10}
>>> dict3 = {"id":3}
>>> list = [dict1, dict2, dict3]
>>> sorted_list = sorted(list, key=lambda x: x['confirmation'], reverse=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
KeyError: 'confirmation'
Update 1
>>> sorted_list = sorted(list, key=lambda x: int(x.get('confirmation', 0)), reverse=False)
>>> sorted_list
[{'id': 3}, {'id': 2, 'confirmation': 10}, {'id': 1, 'confirmation': 20}]