5
votes
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.

5

5 Answers

9
votes

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

My solution:

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

One more, in python 3:

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

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

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.