简体   繁体   English

是否可以在 Python 的字典中移动或交换元素 position?

[英]Is it possible to shift or swap elements position in a dictionary in Python?

if __name__ == '__main__':
    n = int(input())
    for _ in range(n): #n is the number of inputs
        queue = dict(x.split() for x in input().splitlines())
        #queue is a dict that splits the input and store the input as key and value pair.
        for key,value in queue.items():
            print(value,end=' ')
    

Using dictionary as queue to shift or swap elements position in a dictionary in Python使用字典作为队列在 Python 中的字典中移动或交换元素 position

Dictionaries in Python are unordered (or at least, they should be). Python 中的字典是无序的(或者至少应该是无序的)。 In Python 3.6 or later, dictionaries print out in the order they were added, but you should always treat dictionaries as though they are completely unordered.在 Python 3.6 或更高版本中,字典按添加顺序打印,但您应始终将字典视为完全无序。 You can't move values around in a dictionary because, simply put, they aren't in any order, If you want to order them.您不能在字典中移动值,因为简单地说,如果您想对它们进行排序,它们没有任何顺序。 sort the dict.keys() list yourself.自己对 dict.keys() 列表进行排序。

More info here: http://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html#Are-Dictionaries-Ordered?-A-Word-of-Warning更多信息在这里: http://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html#Are-Dictionaries-Ordered?-A-Word-of-Warning

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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