对字典采用两种方式进行排序,但是最后结果不对?
-
采用两种字典排序方式,但是结果都不对,求大佬指导-----
# Untitled - By: PC - 周五 9月 11 2020 import sensor, image, time sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.skip_frames(time = 2000) while(True): img = sensor.snapshot() # one method 排序 c = {3: 56, 5: 87, 2: 889, 1: 0} sorted(c.items(),key = lambda x:x[0], reverse = False) print("c: ", c) print("sor after: ", c) # two method 排序 newDict = {} for i in sorted(c): newDict[i] = c[i] print("i: ", i, newDict[i]) print("new: ", newDict) ![0_1599786333727_1111111.png](https://fcdn.singtown.com/d6d90144-c6d2-4fd5-b9e6-a1cc1c17b25b.png)
-
按照key排序:
c = {3: 56, 5: 87, 2: 889, 1: 0} for i in sorted (c) : print(i,c[i])
结果
>>> 1 0 2 889 3 56 5 87
按照value排序
c = {3: 56, 5: 87, 2: 889, 1: 0} print(sorted(c.items(),key = lambda x:x[1]))
结果
[(1, 0), (3, 56), (5, 87), (2, 889)]