简体   繁体   中英

Reverse Order of a Nested Dictionary Python

I have a two-layered dictionary and would like a simple command or function (if possible) to reverse the order of the dictionary, but only the outer layer, not the inner. For instance, if my dictionary were as follows:

{'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}, 'dictC': {'key_3', 'value_3'}}

and I wanted to instead make it the following:

{'dictC': {'key_3', 'value_3'}, 'dictB': {'key_2': 'value_2'}, 'dictA': {'key_1': 'value_1'}}

How would I do this? I have tried methods like invertdict() and inv_map = {v: k for k, v in my_map.items()} , but I had no success with either.

Any help is appreciated!

Reverse the items:

>>> dict(reversed(d.items()))
{'dictC': {'value_3', 'key_3'}, 'dictB': {'key_2': 'value_2'}, 'dictA': {'key_1': 'value_1'}}

以下代码可以解决问题:

dict(reversed(current_dct.items()))

If your using Python 3.6 or lower, dictionary order is not maintained or guaranteed. What you could do is use a collections.OrderedDict() and applyreversed() to reverse the dictionary:

>>> from collections import OrderedDict
>>> d = {'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}, 'dictC': {'key_3', 'value_3'}}
>>> OrderedDict(reversed(list(d.items())))
OrderedDict([('dictC', {'value_3', 'key_3'}), ('dictB', {'key_2': 'value_2'}), ('dictA', {'key_1': 'value_1'})])

OrderedDict() is a subclass of dict , so it works like a normal dictionary.

However, if you are using a newer version of Python, then dictionary insertion order is maintained. So you could just do the following:

>>> dict(reversed(list(d.items())))
{'dictC': {'value_3', 'key_3'}, 'dictB': {'key_2': 'value_2'}, 'dictA': {'key_1': 'value_1'}}

Note: For safety reasons, its probably better to cast list() to d.items , since older versions pre Python 3.8 don't allow reversing of type dict_items . You will raise a TypeError: 'dict_items' is not reversible error otherwise.

The solutions that implement reversed don't seem to work in older versions of Python ie pre 3.8. This solution should work in Python 3.x

Code

so_dict = {'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}, 'dictC': {'key_3', 'value_3'}}

{k: v for k, v in sorted(list(so_dict.items()), key=lambda x:x[0].lower(), reverse=True)}

Output

{'dictC': {'key_3', 'value_3'},
 'dictB': {'key_2': 'value_2'},
 'dictA': {'key_1': 'value_1'}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM