简体   繁体   中英

Python 2.7: Print a dictionary without brackets and quotation marks

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.

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))

我的解决方案:

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

还有一个,在python 3中:

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

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'])

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM