将OrderedDict转换为普通dict保留顺序? [英] Convert OrderedDict to normal dict preserving order?

查看:366
本文介绍了将OrderedDict转换为普通dict保留顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在保留相同顺序的情况下将OrderedDict转换为普通词典?

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

之所以这样问,是因为当我从API提取数据时,我得到一个JSON字符串,在其中使用json.loads(str)返回字典.从json.loads(...)返回的该词典是乱序的,并且是随机排序的.另外,我已经读到OrderedDict的处理速度很慢,因此我想以与原始JSON字符串相同的顺序使用常规dict.

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.

有点题外话:是否可以使用json.loads(...)将JSON字符串转换为dict,同时不使用collections.OrderedDict保持相同的顺序?

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?

推荐答案

OrderedDict转换为普通dict时,由于字典是无序的,因此不能保证将保留顺序.这就是OrderedDict首先存在的原因.

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.

似乎您想在这里也要吃蛋糕.如果要保留JSON字符串的顺序,请使用我在注释中链接到的问题的答案,将JSON字符串直接加载到OrderedDict中.但是您必须处理所带来的任何性能损失(我不知道这种损失是什么.对于您的用例,它甚至可能是疏忽大意的.).如果要获得最佳性能,请使用dict.但这将是无序的.

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.

这篇关于将OrderedDict转换为普通dict保留顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆