-3

I'm currently trying to sort a dictionary and I've resulted in sorting it as an array like this:

data = {"Craig" : 100, "Bravo" : 99, "Alpha" : 111}

sortlist = list(data.items())
for mx in range(len(sortlist)-1, -1, -1):
    swapped = False
    for i in range(mx):
        if sortlist[i][1] < sortlist[i+1][1]:
            sortlist[i], sortlist[i+1] = sortlist[i+1], sortlist[i]
            swapped = True
    if not swapped:
        break

That returns [('Alpha', 111), ('Craig', 100), ('Bravo', 99)] i now need to be able to grab a value using a name, for instance Alpha would return 111. Does anybody know how to do this.

Thanks in advance

  • 3
    Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – edusanketdk May 02 '21 at 10:13
  • 2
    Did you try changing the list back to a dict? `sortdict = dict(sortlist)` – Tomerikoo May 02 '21 at 10:13

1 Answers1

0

I wrote a function for you (the if statement at the bottom is for testing).

def sort_dict(_dict):
    names = sorted(_dict, key=lambda x: data[x])

    rv = {}
    for name in names:
        rv[name] = data[name]

    return rv

if __name__ == '__main__':
    data = {"Craig" : 100, "Bravo" : 99, "Alpha" : 111}
    sorted_data = sort_dict(data)
    print(sorted_data)
  • There's definitely a more efficient way to do it, but as long as you don't need to sort very long dictionaries it's fine. – NotSirius-A May 02 '21 at 10:18