字典全部为一

时间:2014-04-30 14:05:02

标签: python dictionary

如何在一行中打印所有字典项(键和值)。例如:

dicMyDictionary = {michael:jordan, kobe:bryant, lebron:james} 

print(?)

1 个答案:

答案 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

参考:str.joindict.iteritems

或使用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)

参考:dict.iteritemsPython looping techniques