Convert OrderedDict to normal dict preserving order?

拈花ヽ惹草 提交于 2019-12-25 07:27:33

问题


How do I convert an OrderedDict to a normal dictionary while preserving the same order?

The reason I am asking this is because is when I fetch my data from an API, I get a JSON string, in which I use json.loads(str) to return a dictionary. This dictionary that is returned from json.loads(...) is just out of order and is randomly ordered. Also, I've read that OrderedDict is slow to work with so I want to use regular dict in same order as original JSON string.

Slightly off-topic: Is there anyway to convert a JSON string to a dict using json.loads(...) while maintaining the same order without using collections.OrderedDict?


回答1:


When you convert an OrderedDict to a normal dict, you can't guarantee the ordering will be the preserved, because dicts are unordered. Which is why OrderedDict exists in the first place.

It seems like you're trying to have your cake and eat it too, here. If you want the order of the JSON string preserved, use the answer from the question I linked to in the comments to load your json string directly into an OrderedDict. But you have to deal with whatever performance penalty that carries (I don't know offhand what that penalty is. It may even be neglible for you use-case.). If you want the best possible performance, just use dict. But it's going to be unordered.




回答2:


Both JSON objects and Python dicts are unordered. To preserve order, use JSON arrays which are mapped to Python lists. Elements of JSON arrays should be JSON objects. These will be mapped to Python lists of Python dicts.

Python 3:

from collections import OrderedDict
import json

# Preserving order in Python dict:
ordered_dict = OrderedDict([
    ('a', 1),
    ('b', 2),
    ('c', 3),
])

# Convert to JSON while preserving order:
ordered_list = [{key: val} for key, val in ordered_dict.items()]
json.dumps(ordered_list)
# '[{"a": 1}, {"b": 2}, {"c": 3}]'

Javascript (JSON):

var orderedListStr = '[{"a": 1}, {"b": 2}, {"c": 3}]';
// We will receive this array of objects with preserved order:
var orderedList = JSON.parse(orderedListStr)


来源:https://stackoverflow.com/questions/23965870/convert-ordereddict-to-normal-dict-preserving-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!