Python 2.7: Print a dictionary without brackets and quotation marks

混江龙づ霸主 提交于 2019-12-19 09:06:52

问题


myDict = {"Harambe" : "Gorilla", "Restaurant" : "Place", "Codeacademy" : "Place to learn"}

So, I want to print out a dictionary. But I want to do it like it looks like an actual list of things. I can't just do print myDict, as it will leave all the ugly stuff in. I want the output to look like Harambe : Gorilla, Restaurant : Place, etc

So what do I do? I haven't found a post meeting what I want. Thanks in advance.


回答1:


Using the items dictionary method:

print('\n'.join("{}: {}".format(k, v) for k, v in myDict.items()))

Output:

Restaurant: Place
Codeacademy: Place to learn
Harambe: Gorilla

Expanded:

for key, value in myDict.items():
    print("{}: {}".format(key, value))



回答2:


My solution:

print ', '.join('%s : %s' % (k,myDict[k]) for k in myDict.keys())



回答3:


I'm not sure if this is a python 3.x thing (first post btw), but I had this problem with dictionaries within a list and figured out this worked for me:

list = [
 {'Key1': 'Value1', 'Key2': 'Value2'},
 {'Key1': 'Value1', 'Key2': 'Value2'}
 ]

for i in list:
 print('Key1: ', i['Key1'], 'Key2: ', i['Key2'])



回答4:


You could try something like this.

for (i, j) in myDict.items():
    print "{0} : {1}".format(i, j), end = " " 

Note that since dictionaries don't care about order, the output will most likely be more like Restaurant : Place Harambe : Gorilla Codeacademy : Place to learn.




回答5:


One more, in python 3:

print(*['{} : {}'.format(k,v) for k,v in myDict], sep = "\n")


来源:https://stackoverflow.com/questions/40071006/python-2-7-print-a-dictionary-without-brackets-and-quotation-marks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!