[英]How can I print from a dictionary?
I am wondering how I can print all keys in a dictionary on one line and values on the next so they line up. 我想知道如何才能将字典中的所有键打印在一行上,而值又打印在下一行,以便它们对齐。
The task is to create a solitaire card game in python. 任务是用python创建纸牌纸牌游戏。 Made most of it already but I wish to improve on the visual.
已经完成了大部分操作,但是我希望在视觉效果上有所改善。 I know how to use a for loop to print lines for each value and key, but the task I'm doing in school asks me to do it this way.
我知道如何使用for循环为每个值和键打印行,但是我在学校正在做的任务要求我这样做。 I also just tried to create new lists for each line and "print(list1)" print(list2) but that just looks ugly.
我还尝试为每行和“ print(list1)” print(list2)创建新列表,但这看起来很丑。
FireKort ={
'A': None,#in my code i have the cards as objects here with value
#and type
'B': None,#ex. object1: 8, cloves; object2: King, hearts
'C': None,
'D': None,
'E': None,
'F': None,
'G': None,
'H': None
}
def f_printK():
global FireKort
for key in FireKort:
print('Stokk:',key,' Gjenstående:',len(FireKort[key]))
try:
print(FireKort[key][0].sort, FireKort[key][0].valør)
except:
print('tom')
##here are the lists i tried:
## navn=[]
## kort=[]
## antall=[]
## for key in FireKort:
## navn.append((key+' '))
## kort.append([FireKort[key][0].sort,FireKort[key][0].valør])
## antall.append( str(len(FireKort[key])))
## print(navn)
## print(kort)
## print(antall)
ABCDEFGH [♦9][♣A][♠Q][♣8][♦8][♣J][♣10][♦7] 4 4 4 4 4 4 4 4 ABCDEFGH [♦9] [♣A] [♠Q] [♣8] [♦8] [♣J] [♣10] [♦7] 4 4 4 4 4 4 4 4 4
Have you try to use pprint
? 您尝试使用
pprint
吗?
The pprint module provides a capability to “pretty-print arbitrary Python data structures
pprint模块提供了“漂亮地打印任意Python数据结构的功能”。
https://docs.python.org/2/library/pprint.html https://docs.python.org/2/library/pprint.html
Try this: 尝试这个:
d = { ... }
keys = [ str(q) for q in d.keys() ]
values = [ str(q) for q in d.values() ]
txts = [ (str(a), str(b)) for a, b in zip(keys, values) ]
sizes = [ max(len(a), len(b)) for a, b in txts ]
formats = [ '%%%ds' % q for q in sizes ]
print(' '.join(a % b for a, b in zip (formats, keys)))
print(' '.join(a % b for a, b in zip (formats, values)))
In short: 简而言之:
It could be done using ljust
method of str
. 可以使用
str
ljust
方法来完成。 Example: 例:
d = {'A':'some','B':'words','C':'of','D':'different','E':'length'}
keys = list(d.keys())
values = list(d.values())
longest = max([len(i) for i in keys]+[len(i) for i in values])
print(*[i.ljust(longest) for i in keys])
print(*[i.ljust(longest) for i in values])
Output: 输出:
A B C D E
some words of different length
Note that I harnessed fact that .keys()
and .values()
return key and values in same order, if no action was undertaken between them regarding given dict
. 请注意,如果没有对给定
dict
进行任何操作,我会利用.keys()
和.values()
返回键和值的顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.