How could reorder the keys in the dictionary?


#1

I have a dictionary. {key: value, key2: value2}, Dict = {(4, 5): (2.733), (5, 2): (2.4533), (6, 2): (4.533), (7, 3): (1.333)}.
How could I reorder the key part to NewDict = {(0, 1): (2.733), (0, 2): (2.4533), (1, 0): (4.533), (1, 1): (1.333)}

This is what I do. But it does’t reordered the number as I want.

Imax = Max(Dict.keys()[0])
jmax = Max(max.keys()[1])
values= Dict.value()
for m in range(Imax ):

for k in range(jmax ):

NewDict [(k,m)] = values[m]


(Steve Baer) #2

Dictionaries don’t maintain data in the order that you add them. If you want something with a defined order, you probably want to use a list.


(Menno Deij - van Rijswijk) #3

First hit in a google search

#dictionary is in the variable d
sorted(d, key=d.get)
# or
sorted(d, key=lambda key: d[key])

(Steve Baer) #4

Yep, and the sorted function returns a list.


#5

thanks for the reply.
What I want is not sort the dictionary. But only rewrite the key, not the values. so the values keep the same,but replace the keys by their index in the dictionary.


(Steve Baer) #6

Then you should get a sorted list of keys based on running the sorted function on the d.keys(). Use that list to remap your dictionary. I don’t have access to my computer at the moment, so I can’t put a good sample together but hopefully what I’m explaining makes sense.


#7

thanks for the note. what’s the d.get mean?


#8

Here is the example for what I want. How do I sort the key = (i,j)

Pt = {}
for i in range(5):

for j in range(5):

x = i
y = j
z=0
Pt[(i,j)] = (x,y,z)

#for this dictionary If I Take 3 index out like NewDict {(4, 3): (4, 3, 0), (0, 0): (0, 0, 0), (1, 3): (1, 3, 0)}
rewrite the key (k,m) in the same sequence to the older (i,j).
The result I want is {(0,0):(0, 0, 0),(0, 1): (1, 3, 0), (1, 1): (4, 3, 0) }


(Steve Baer) #9
# d is your old dictionary
sortedkeys = sorted(d.keys(), key=lambda x,y:x*10000+y)
current_x = -1
current_y = 0
row = None
new_d = {}
for key in sortedkeys:
    x,y = key
    if x != row:
        row = x
        current_x = current_x + 1
        current_y = 0
    else:
        current_y = current_y + 1
    new_d[(current_x, current_y)] = d[key]

There are propably typos here since I’m posting from an ipad, but hopefully you understand.