Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Dictionary Keys without Dictionary Name? How/why?

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:

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

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

  3. On a side note, how can I print keys or other elements like lists, tuples, etc without the string quotes (')?

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

thanks and cheerio :-)

like image 988
Newbie Avatar asked Nov 28 '12 20:11

Newbie


People also ask

How do I print just the key in a dictionary?

keys() method can be used to retrieve the dictionary keys, which can then be printed using the print() function.

Why can't a list be a dictionary key?

For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable. Values, on the other hand, can be any type and can be used more than once.

Why must dictionary keys be unique?

No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.

How do you fetch and display only the keys of a dictionary in python?

Python Dictionary keys() method. The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python. Parameters: There are no parameters. Returns: A view object is returned that displays all the keys.


1 Answers

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.

like image 67
Lev Levitsky Avatar answered Sep 28 '22 08:09

Lev Levitsky