如何从左到右打印字典的值?

2024-05-19 14:13:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典:

a = {"w1": "wer", "w2": "qaz", "w3": "edc"}

当我试图打印它的值时,它们是从右向左打印的:

^{pr2}$

我要从左到右打印:

wer qaz edc

我该怎么做?在


Tags: 字典edcw1werw3w2pr2qaz
2条回答

假设您希望它们按键的字母顺序排列,可以执行以下操作:

a = {"w1": "wer", "w2": "qaz", "w3": "edc"}  # your dictionary

keylist = a.keys()   # list of keys, in this case ["w3", "w2", "w1"]
keylist.sort()       # sort alphabetically in place, 
                     #  changing keylist to ["w1", "w2", w3"]

for key in keylist:
    print a[key]     # access dictionary in order of sorted keys

你不能。字典没有你可以使用的任何顺序,所以字典文字没有“从左到右”的概念。决定分类,并坚持下去。在

相关问题 更多 >