anonymous-explorer
anonymous-explorer

Reputation: 415

how to rearrange the order of dictionary keys?

I'm facing a problem where I want to rearrange the order of dictionary keys. I have an array which has env = [key1, key2, key3] and then in a loop these keys are being fetched from array and fed to a dictionary; dict_result. dic_result shows the order of these env keys in dictionary in below format(based on alphabetical order of the names of key1, key2, 3 even though i didn't use any sorted function):

{'name': {'key2': [val1, val2, val3], 'key1': [], 'key3': [val1, val2]},
'name1': {'key2': [val1, val2, val3], 'key1': [], 'key3': [val1, val2]},
...
}

for k in dict_result['name'].keys():
    //performing checks 

I want to change the order of nested keys for dict_result[name]to look like :

{'name': {'key3': [val1, val2]}, 'key2': [],'key1': [val1, val2, val3]}

I did give a try using inbuilt function reversed() but it seems to create an iterator which change quite some logic in my existing code and for loop that is iterating over these dictionary env keys and performing checks/validations based on its values. I now understand that a regular dict doesn’t track the insertion order, and iterating it gives the values in an arbitrary order.

Kindly help if there is an easier way to either have dictionary consume the env keys exactly in the same order they are being fed/ingested from array i.e. key1, key2, key 3 or just can reverse it to have key3, key 2, key1. But don't want the existing way it is showing alphabetical order based on the actual key names.

Upvotes: 5

Views: 6466

Answers (5)

Rahul charan
Rahul charan

Reputation: 837

With the help of reversed() keyword, you can get your result:-

val1,val2,val3 = 1,2,3
dict_result = {'name': {'key3': [val1, val2, val3], 'key2': [], 'key1': 
 [val1, val2]}}
old_key = dict_result['name'].keys()
old_key = list(old_key)
new_key = list(reversed(old_key))
#print(new_key)
value = []
for k in new_key:
    value.append(dict_result['name'][k])
zip_key_value = list ( zip(new_key, value) )
temp_dict = dict(zip_key_value)
new_dict_result = {'name':temp_dict}

print(dict_result)
print(new_dict_result)

Output

{'name': {'key3': [1, 2, 3], 'key2': [], 'key1': [1, 2]}}
{'name': {'key1': [1, 2], 'key2': [], 'key3': [1, 2, 3]}}

I hope it may help you.

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71570

An one-liner dictionary-comprehension:

print({k: dict(zip(list(v.keys())[::-1], list(v.values())[::-1])) for k, v in dict_result.items()})

This works for any amount of keys.

Upvotes: 1

bharatk
bharatk

Reputation: 4315

OrderedDict could be used to maintain the insertion-ordering, once the keys are sorted.

import collections

data = {'name': {'key3': [1, 2, 3], 'key2': [], 'key1': [5, 6]}}
data['name'] = sorted(data['name'].items())
order_dict = collections.OrderedDict(data)
print(order_dict)

O/P:

OrderedDict([('name', [('key1', [5, 6]), ('key2', []), ('key3', [1, 2, 3])])])

Upvotes: 2

rokitoker
rokitoker

Reputation: 101

Possible solution:

from collections import OrderedDict
my_dictionary=OrderedDict()
for i in (old_dict.keys()):
    my_dictionary[i]=b[i]

Upvotes: 0

lmiguelvargasf
lmiguelvargasf

Reputation: 69735

I think you could update this particular dictionary:

dict_result['name'] = {key: dict_result['names'][key] for key in sorted(dict_result['name'].keys())}

Upvotes: 0

Related Questions