So I want to change the order in a dictionary of two key:values
The example is:
dico = {'a': [0, 0, '-', 'b'], 'b': [0, 0, 'c', 'd'], 'c': [1, 0, 'a', 'b'], 'd': [0, 0, 'c', '-']}
I want to change the order between the key 'b' and 'c' like this:
dico = {'a': [0, 0, '-', 'b'], 'c': [1, 0, 'a', 'b'], 'b': [0, 0, 'c', 'd'], 'd': [0, 0, 'c', '-']}
I don't wanna use any method or function like (sorted etc...)
If you know how to do, it would be very grateful.
Thank you.
CodePudding user response:
Keys are stored in dict in insertion order.
If you really want to you can re-order all keys like this:
key_order = ['a', 'c', 'b', 'd']
dico = {k : dico[k] for k in key_order}
CodePudding user response:
Given the example dictionary data in Python language, you should change the position of two keys ‘b’
and ‘c’
. However, in dictionary type, keys cannot change directly. Using keys()
function and list()
function, you have to make another list data named keys
which consists of every key in dico
dictionary data. As Python language counts indices on the zero-based, the first key should be ‘c’
and second key should be ‘b’
. Next, use a for
loop to reflect the original values of dico
dictionary data.
The following source code in Python language is an example for a suggestion. I hope it’ll work well for you.
dico = {'a': [0, 0, '-', 'b'], 'b': [0, 0, 'c', 'd'], 'c': [1, 0, 'a', 'b'], 'd': [0, 0, 'c', '-']}
keys = list(dico.keys())
keys[1] = 'c'
keys[2] = 'b'
for k in keys:
dico[k] = dico.pop(k)
print(dico)