如何在一行中打印所有字典项(键和值)。例如:
dicMyDictionary = {michael:jordan, kobe:bryant, lebron:james}
print(?)
答案 0 :(得分:2)
首先,只需打印字典本身就可以在一行上打印所有内容:
>>> dicMyDictionary = {"michael":"jordan", "kobe":"bryant", "lebron":"james"}
>>> print(dicMyDictionary)
{'kobe': 'bryant', 'michael': 'jordan', 'lebron': 'james'}
如果您想以某种方式格式化它:
>>> print(' '.join(str(key)+":"+str(value) for key,value in dicMyDictionary.iteritems()))
kobe:bryant michael:jordan lebron:james
或使用for
循环进行更详细的控制:
>>> formatted_str = ""
>>> for key,value in dicMyDictionary.iteritems():
formatted_str += "(key: " + str(key) + " value:" + value + ") "
>>> print(formatted_str)
(key: kobe value:bryant) (key: michael value:jordan) (key: lebron value:james)