Hi.

I want to sort the keys of my dictionary.
The keys are consisted of list of 3 different numbers, for instance - (0, 5, 0)
So I want to sort them first over key[2], then over key[1] and then over key[0]
Then to print the value accorfing to the sorted keys
The keys should be sorted like this:
0 0 0
5 0 0
0 5 0
5 5 0
0 0 5
5 0 5
0 5 5
5 5 5

Thank you very much

Recommended Answers

All 7 Replies

If I use :
for key in sorted(dictionary.items()):
print dictionary[key]

how can I specify there the specific way of sorting the keys?

You can add key for sorting to sorted, for example
sorted(dictionary,key = reversed)

That doesn't really work.

I did it by comparing the keys with a sorted list starting from the last key[2].
I was thinking maybe there is another easier way to do taht...

Thank you all
xxx

data = """0 0 0
5 0 0
0 5 0
5 5 0
0 0 5
5 0 5
0 5 5
5 5 5
"""

mydict={tuple(int(b) for b in a.split()) : a
        for a in data.splitlines()}
for item in sorted(mydict, key = lambda x : x[::-1]):
    print item,mydict[item]
commented: nice slicing trick +12

Hey !!
The sorting does work!!!

You don't give up :) even after I had closed the thread :)

Thank you very much

You just post your last efforts also and cry to us regulars' shoulder. So if you had enough swea.. I mean learning experience so we can fix the last bits. It is educating to try yourself (reason we did not give ready solution) but it is also necessary to get it solved in the end, even with other's help.

Well my solution works as well, just looking for a better one :)
And I started working with Python just a week ago so yes you are right I do not have enough experience.
Some good help is really appreciated.
Thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.