![](/img/trans.png)
[英]Properly formatting a string given a python dictionary with keys that are tuples
[英]Formatting a python dictionary of tuples?
我現在有以下輸出:
{ ('JAIL','A'): 20, ('BAIL','J'): 50, ('ZERO','D'): 80, ('LIME', 'A'): 24 }
我想按字典中元組的第一個字符串對字典進行排序。 然后,我想顯示輸出如下:
BAIL -> J 50
JAIL -> A 20
LIME -> A 24
ZERO -> D 80
您可以使用sorted
方法
myDict = { ('JAIL','A'): 20, ('BAIL','J'): 50, ('ZERO','D'): 80, ('LIME', 'A'): 24 }
for l, v in sorted(myDict.items()):
print "{} -> {} {}".format(l[0], l[1], v)
產量
BAIL -> J 50
JAIL -> A 20
LIME -> A 24
ZERO -> D 80
使用sorted
和元組拆包:
>>> myDict = {('JAIL','A'):20, ('BAIL','J'):50, ('ZERO','D'):80, ('LIME','A'):24}
>>> for (word, ch), value in sorted(myDict.items()):
... print('{} -> {} {}'.format(word, ch, value))
...
BAIL -> J 50
JAIL -> A 20
LIME -> A 24
ZERO -> D 80
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.