简体   繁体   中英

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

Dictionaries in Python are unordered (or at least, they should be). 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. 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.

More info here: http://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html#Are-Dictionaries-Ordered?-A-Word-of-Warning

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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