Python dictionary structure sorting and taking the first few items
Dictionary data structure
Below is the dictionary data structure I need to process
{
'一家': 0.026705843302086574, '三口': 0.03863159743158114, '搬家': 0.10736427147319758, '新家': 0.08690615802706024, '得来': 0.054637067219615684, '买来': 0.04612577908469612,..........,'新房子': 0.038974785884171845, '搬进': 0.09108143118667884}
Convert dictionary to list structure and sort
Sort according to the second field, which is the value.
list = sorted(dict.items(), key=lambda d: d[1], reverse=True)
Here dict is to save the above data.
dict.items() is the list to be sorted;
key=lambdad: d[1] is the input d, and sorts the value of the second-dimensional data in the previous d.
The processed data is as follows:
[('东西', 0.13536804201443886), ('收拾', 0.11559750288801565), ('搬家', 0.10736427147319758),..........., ('小东西', 0.0947239858845381), ('坟', 0.0929545414763724)]
This is after the data has been converted into an ordered List structure, it is easy to fetch the data later.
Get the top 10 items
Here is a stupid way ~ traverse to take out the first 10 items, so if the data does not have 10 items, there will be no error.
new_list = []
num = 10
for item in list:
if num == 0:
break
else:
new_list.append(item)
num = num - 1
The web upload also passed list.sublist(end,start). I tried it and reported an error. I couldn't find the sublist method. I don't know what's wrong, so I just used the above method.
Big guys are welcome to criticize and correct!