0
def keyword_arguments(**keywords):
    return sorted(keywords.keys())

if __name__ == '__main__':
    print keyword_arguments(arg1 = 1, arg2 = 2, arg3 = 3)

the above code returns ['arg1', 'arg2', 'arg3'] correctly. However, if I replace the return statement in the function like so:

return keywords.keys().sort()

it returns None. Why is this?

1
  • 2
    Because sort returns None. Commented May 14, 2014 at 6:00

1 Answer 1

2

This is because sort() returns None. It just sorts the list in place. You should do:

return sorted(keywords.keys())

Demonstration

a = [2,3,1]
>>> print a.sort()
None
>>> print a
[1, 2, 3]

Alternative

a = keywords.keys()
a.sort()
return a
Sign up to request clarification or add additional context in comments.

6 Comments

Why not return keywords and leave out a
return a will still return None in that example
@TimCastelijns, Because the dictionary would still remain unsorted
@TimCastelijns, I agree, but when you do keyword.keys(), you are getting the dictionary keys as a separate list, Then you would sort them and then they just get discarded. You still end up returning the unordered dictionary keys because the next time you do keyword.keys() for returning them, it takes them from the dictionary again.
Yes I got confused after your edit :-P already removed that comment
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.