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.
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.
use asterisk '*' operator to print a list without square brackets.
You can simply use the strip() function like so: >>> "[In Python, how do you remove...]". strip("[]")
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))
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'])
My solution:
print ', '.join('%s : %s' % (k,myDict[k]) for k in myDict.keys())
One more, in python 3:
print(*['{} : {}'.format(k,v) for k,v in myDict], sep = "\n")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With