Python 2.7: Print a dictionary without brackets and quotation marks
21,645
Solution 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))
Solution 2
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'])
Solution 3
My solution:
print ', '.join('%s : %s' % (k,myDict[k]) for k in myDict.keys())
Solution 4
One more, in python 3:
print(*['{} : {}'.format(k,v) for k,v in myDict], sep = "\n")
Author by
m1ksu
Updated on July 09, 2022Comments
-
m1ksu almost 2 years
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 likeHarambe : Gorilla, Restaurant : Place, etc
So what do I do? I haven't found a post meeting what I want. Thanks in advance.