简体   繁体   中英

Cannot convert a dictionary into list of tuples and sort it

I want to find outliers keys (names) in my dataset, so that I am trying to create a list of tuples from my dictionary and sort them by salary. That is my code

for key, value in data_dict.iteritems():
    sorted_dict_list = []
    sorted_dict_list.append((key, value["salary"], value["bonus"]))
    sorted_dict_list.sort(key=lambda tup: tup[1])
    for tuple in sorted_dict_list:
        print tuple

The problem is that the printed output is unsorted. What might be the problem?

You should declare sorted_dict_list outside the first for loop, otherwise each time you go through the loop you have a new empty list. On top of that, your loop through sorted_dict_list is inside the first for loop.

So each time you loop through the outer loop you create an empty list, add the next key-value pair into it, run through the list (which is only one item long) and print out the values. Basically you are just printing out each key-value pair as you go through.

You need to move the list declaration outside the loop and un-indent the second loop.

sorted_dict_list = []
for key, value in data_dict.iteritems():
    sorted_dict_list.append((key, value["salary"], value["bonus"]))
    sorted_dict_list.sort(key=lambda tup: tup[1])

for tuple in sorted_dict_list:
    print tuple

This might be a better solution:

def sortKey(item):
    return item[1]

sorted_dict = [(key, value['salary'], value['bonus']) for key, value in data_dict.items()]
sorted_dict = sorted(sorted_dict, key=sortKey)

for item in sorted_dict:
    print(item)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM