我试图在python中整齐地打印一本字典,但不确定如何这样做。
如果我有字典
mydict = {'Jackson' :['One', 'Two', 'Three'], 'Jeffery' :['Four', 'Five', 'Six']}
我将如何将其打印出来:
Jackson One Two Three
Jeffery Four Five Six
我猜我必须使用for循环,只是想弄清楚如何打印出列表组件。
答案 0 :(得分:1)
解决此问题的另一种方法,
def printDictionary(mydict):
for i in mydict.keys():
print(i + " " + (" ".join(mydict[i])))
mydict = mydict = {'Jackson' :['One', 'Two', 'Three'], 'Jeffery' :['Four', 'Five', 'Six']}
printDictionary(mydict)
答案 1 :(得分:0)
在Python3.6中,您可以使用f
字符串
>>> mydict = {
... 'Jackson' :['One', 'Two', 'Three'],
... 'Jeffery' :['Four','Five', 'Six']
... }
>>> for k,v in mydict.items():
... print(f"{k} {' '.join(v)}")
...
Jackson One Two Three
Jeffery Four Five Six
在旧版本的3.x中,您可以使用按键格式
>>> for k,v in mydict.items():
... print("{k} {vstr}".format(k=k, vstr=" ".join(v)))
...
Jackson One Two Three
Jeffery Four Five Six
或位置
>>> for k,v in mydict.items():
... print("{} {}".format(k, " ".join(v)))
...
Jackson One Two Three
Jeffery Four Five Six
如果你想要简洁,你也可以只使用元组解包(但如果你需要改变输出格式,那就非常灵活了)
>>> for k, v in mydict.items():
... print(k, *v)
...
Jackson One Two Three
Jeffery Four Five Six
答案 2 :(得分:0)
for key in mydict:
print(key,end=' ')
for i in mydict[key]:
print(i,end='')
print("\n")