将字典 python 中的元素移动到另一个索引

mat*_*ewr 3 python dictionary python-3.x

例如,如果我有这样的字典:

dicta={1:['a','a','a'],2:['b,'b','b'],'N':['n','n','n'],3:['c','c','c']}
Run Code Online (Sandbox Code Playgroud)

我希望 N 位于最后一个位置,因为我稍后将此 dict 转换为 df。有没有办法向下移动?

找到 N 的索引很好: index=list(dicta.keys()).index('N')

但是你会怎么做(用伪代码)dicta.position[-1] = dicta[index]位呢?

Kas*_*mvd 7

您可以通过popping将一个项目移到最后,然后将其重新分配给字典。

>>> dicta = {1: 'a', 2: 'b', 'N': 'n', 3: 'c'}
>>> dicta['N'] = dicta.pop('N')
>>> dicta
{1: 'a', 2: 'b', 3: 'c', 'N': 'n'}
Run Code Online (Sandbox Code Playgroud)

这仅在您使用CPython 3.6+或任何其他以3.7开头的 Python 实现时才有效,因为dict在这些版本之前没有插入顺序。