[英]OrderedDict move_to_end alternative for Python 3.5+
I have a dict with n parameters:我有一个带有 n 个参数的字典:
print(table)
{
"Parameters":{
"erVersion":"1.0",
"A":"a",
"rVersion":"1.0",
"B":"b",
"C":"c",
"Ur":"legislator",
"RecordSize":"13",
"classification":"json",
"compressionType":"none"
}
}
I wanted to place the parameters A, B and C to the top of parameters.我想将参数 A、B 和 C 放在参数的顶部。 I tried doing this with the following code:我尝试使用以下代码执行此操作:
table['Parameters'].move_to_end("C", last=False)
table['Parameters'].move_to_end("B", last=False)
table['Parameters'].move_to_end("A", last=False)
This however doesn't work as of Python 3.5+ (refference: https://stackoverflow.com/a/16664932/7615751 )但是,从 Python 3.5+ 起,这不起作用(参考: https://stackoverflow.com/a/16664932/7615751 )
Is there an alternative to this with newer versions of Python?更新版本的 Python 是否有替代方案? If a different approach is better I'd also appreciate the suggestion to use it.如果另一种方法更好,我也会很感激使用它的建议。
I don't want to solve this by defining a fixed parameter order because I have a lot of tables like this with a different number of parameters (they always have the A, B, C parameter though).我不想通过定义一个固定的参数顺序来解决这个问题,因为我有很多这样的表,它们的参数数量不同(尽管它们总是有 A、B、C 参数)。
Let's assume让我们假设
data = {
"Parameters":{
"erVersion":"1.0",
"A":"a",
"rVersion":"1.0",
"B":"b",
"C":"c",
"Ur":"legislator",
"RecordSize":"13",
"classification":"json",
"compressionType":"none"
}
}
You seem to be doing table = OrderedDict(data)
, which will create said object for only the key 'Parameters'.你似乎在做table = OrderedDict(data)
,这将只为关键的“参数”创建所说的 object。 The value of that, ie, the inner dictionary, will remain a normal dict
, which doesn't support move_to_end()
.它的值,即内部字典,将保持正常的dict
,它不支持move_to_end()
。 You can address that with你可以解决这个问题
table['Parameters'] = OrderedDict(table['Parameters'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.