So I created a dictionary for setting difficulty level on a little game.
diff_dict = {'easy':0.2, 'medium':0.1, 'hard':0.05} # difficulty level dict
Keys are going to be the difficulty names and the values some ratios that i would use to compute the difficulty.
So I was trying to figure out how to print only the keys to the user:
print('\nHere are the 3 possible choices: ',diff_dict.keys())
this would print as:
Here are the 3 possible choices: dict_keys(['hard', 'easy', 'medium'])
Obviously I don't want to have the dictionary name displayed so I continued to search and I did find a solution which works:
diff_keys = diff_dict.keys()
print ('\nHere are the 3 possible choices: ',list(diff_keys))
But I still want to know if there are other methods to achieve this, then why and so on. So here I go with the Qs:
Can I achieve the same result without crating a new element, such as diff_keys?
Why does
diff_dict.keys
display the dict. name? Am I doing something wrong?On a side note, how can I print keys or other elements like lists, tuples, etc without the string quotes (')?
same as #3 above but the brackets ([ ])
thanks and cheerio :-)
The thing is, in Python 3 dict's method
keys()
does not return a list, but rather a special view object. That object has a magic__str__
method that is called on an object under the hood every time youprint
that object; so for view objects created by callingkeys()
__str__
is defined so that the resulting string includes"dict_keys"
.Look for yourself:
Note that 99.9% of the time you don't need to call this method directly, I'm only doing it to illustrate how things work.
Generally, when you want to print some data, you almost always want to do some string formatting. In this case, though, a simple
str.join
will suffice:So, to answer you questions:
An example is shown above.
Because its
__str__
method works that way. This is what you have to deal with when printing objects "directly".Print them so that their
__str__
is not called. (Basically, don't print them.) Construct a string in any way you like, crafting your data into it, then print it. You can use string formatting, as well as lots of useful string methods.