Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

python - Converting List into Dictionary of Sorted Tuples

I've used the following approach many times to generate a list of tuples from the contents of a dictionary:

dispositions = list(dispositions.items())

In this case, the keys are different types of ways a patient can leave the emergency department, and the values are counts of those types. Now, I wanted to sort this data based on the second item in each of the tuples, so I tried this:

dispositions = list(dispositions.items()).sort(key=lambda x: x[1])

To my surprise, when I ran the code, I found that dispositions had been set to None. I tried breaking it into two parts, as follows:

dispositions = list(dispositions.items())
dispositions.sort(key=lambda x: x[1])

This works! I got my list of sorted tuples. So, I've already solved my problem, but I want to know why the first option didn't work so that I can be a better person (better programmers are better people). Can anyone help me out here?

question from:https://stackoverflow.com/questions/65909352/converting-list-into-dictionary-of-sorted-tuples

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

list.sort does not return anything. So this:

dispositions = list(dispositions.items()).sort(key=lambda x: x[1])

sets dispositions to None.

sorted on the other hand returns a new list. So you would use:

dispositions = sorted(dispositions.items(), key=lambda x: x[1])

Which will set dispositions to a sorted list of tuples.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...