Print Dictionary Keys without Dictionary Name? How/why?

后端 未结 1 1641
無奈伤痛
無奈伤痛 2021-01-19 14:54

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
<         


        
相关标签:
1条回答
  • 2021-01-19 15:35

    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 you print that object; so for view objects created by calling keys() __str__ is defined so that the resulting string includes "dict_keys".

    Look for yourself:

    In [1]: diff_dict = {'easy': 0.2, 'medium': 0.1, 'hard': 0.05}
    
    In [2]: print('Here are the 3 possible choices:', diff_dict.keys())
    Here are the 3 possible choices: dict_keys(['medium', 'hard', 'easy'])
    
    In [3]: diff_dict.keys().__str__()
    Out[3]: "dict_keys(['medium', 'hard', 'easy'])"
    

    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:

    In [4]: print('Here are the 3 possible choices:', ', '.join(diff_dict))
    Here are the 3 possible choices: medium, hard, easy
    

    So, to answer you questions:

    Can I achieve the same result without crating a new element, such as diff_keys?

    An example is shown above.

    Why does diff_dict.keys display the dict. name? Am I doing something wrong?

    Because its __str__ method works that way. This is what you have to deal with when printing objects "directly".

    how can I print keys or other elements like lists, tuples, etc without the string quotes (')?

    same as #3 above but the brackets ([ ])

    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.

    0 讨论(0)
提交回复
热议问题