Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 977
m1ksu Avatar asked Oct 16 '16 13:10

m1ksu


People also ask

How do you print a dictionary without brackets and quotes in Python?

You can use slicing on the string representation of a dictionary to access all characters except the first and last ones—that are the curly bracket characters. For example, the expression print(str({'a': 1, 'b': 2})[1:-1]) prints the list as 'a': 1, 'b': 2 without enclosing brackets.

How do you print without brackets in Python?

use asterisk '*' operator to print a list without square brackets.

How do I remove square brackets from a dictionary in Python?

You can simply use the strip() function like so: >>> "[In Python, how do you remove...]". strip("[]")


4 Answers

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))
like image 82
idjaw Avatar answered Oct 19 '22 23:10

idjaw


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'])
like image 40
Inteligent Avatar answered Oct 20 '22 00:10

Inteligent


My solution:

print ', '.join('%s : %s' % (k,myDict[k]) for k in myDict.keys())
like image 34
mkj Avatar answered Oct 19 '22 22:10

mkj


One more, in python 3:

print(*['{} : {}'.format(k,v) for k,v in myDict], sep = "\n")
like image 42
volody Avatar answered Oct 19 '22 23:10

volody