I'm trying to sort a dictionary that contains binary strings but it doesn't seem to sort properly. The code I used is below:
dict1 = {"5": "101", "1": "001", "17": "10001", "3" : "11"}
print("Unsorted dict:",dict1)
sorted_tuples = sorted(dict1.items(), key=lambda item: item[1])
print("Sorted tuples:",sorted_tuples)
sorted_dict = {k: v for k, v in sorted_tuples}
print("Sorted dict:",sorted_dict)
I expected the output to be:
Unsorted dict: {'5': '101', '1': '001', '17': '10001', '3': '11'}
Sorted tuples: [('3', '11'), ('1', '001'), ('5', '101'), ('17', '10001')]
Sorted dict: {'3': '11', '1': '001', '5': '101', '17': '10001'}
The reason I thought 11 would come before 001 is that 11 is two charcters and 001 is three. This, I assumed, would continue and a five character string would be sorted after a two character string.
However, the output I do get is:
Unsorted dict: {'5': '101', '1': '001', '17': '10001', '3': '11'}
Sorted tuples: [('1', '001'), ('17', '10001'), ('5', '101'), ('3', '11')]
Sorted dict: {'1': '001', '17': '10001', '5': '101', '3': '11'}
The keys for each value are just symbolic, so it's easier to show. The important parts are the values - they're what I want to sort.
Any suggestions please?