更新时间:2021-12-19 06:09:35
您的自我回答就像您所说的那样冗长而繁琐。不必如此。如果(1)超过10个键(2)字典的键数少于预期,也会失败。
Your self-answer is as you said long and cumbersome. It doesn't need to be. Also it will fail if (1) there are more than 10 keys (2) a dict has fewer keys than than expected.
尝试一下;它要简单得多:
Try this; it's much simpler:
>>> ordered_keys = ('z', 'y', 'e', 'x', 'w') # possible keys, in desired order
注意:上面的行是必需的所有设置。
Note: the above line is all the setup that is required.
>>> dic = {'z':'a', 'y':'b', 'x':'c', 'w':'d'} # actual contents of a dictionary
>>> for k in ordered_keys:
... if k in dic: # avoid trouble if a key is missing
... print k, dic[k]
...
z a
y b
x c
w d
>>>