1

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}]

2 Answers 2

3

You can use dict.get to suppress KeyError supplying a default value of 0:

sorted_list = sorted(lst, key=lambda x: int(x.get('confirmation', 0)), reverse=True)

Also, remember to convert the string values to a numerical type, so the sorting is numerical not lexicographical.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use dict.get function to assign default value of 0 to "confirmation" key, if the key is not present in the dict.

lst = [
    {
      'id':'1',
      'confirmation':'20',
    },
    {
      'id':'2',
      'confirmation':'10',
    },
    {
      'id':'3'
    }
]
sorted_list = sorted(lst, key = lambda x : int(x.get('confirmation',0)))
print sorted_list

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.