打印字典键没有字典名称?如何/为什么? [英] Print Dictionary Keys without Dictionary Name? How/why?

查看:144
本文介绍了打印字典键没有字典名称?如何/为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我创建了一个字典来设置一个小游戏的难度级别。

  diff_dict = {'easy':0.2,'medium':0.1,'hard':0.05}#难度等级dict 

键将成为难度名称和值,我将用来计算难度的一些比例。



所以我试图找出如何仅打印用户的密钥:

  print('\\\
ere 3个可能的选择:',diff_dict.keys())

这将打印为:

 以下是3种可能的选择:dict_keys(['hard','easy ','medium'])

显然我不想让字典名称显示,所以我继续搜索,我找到了一个解决方案:

  diff_keys = diff_dict.keys()
print \\\
n是3种可能的选择:',list(diff_keys))

但是我还是想知道有没有其他的方法来交流隐藏这个,那么为什么等等。所以这里我去问Qs:


  1. 我可以实现相同的结果,而不用包装一个新的元素,如diff_keys? / p>


  2. 为什么 diff_dict.keys 显示dict。名称?我做错了什么?


  3. 在旁注中,如何打印键或其他元素,如列表,元组等没有字符串引号(') ?


  4. 与上述#3相同但括号([])


谢谢和cheerio: - )

解决方案

事情是,在Python 3 dict的方法 keys()不返回列表,而是一个特殊的查看对象。该对象具有魔术 __ str __ 方法打印时,在引擎盖下的对象上调用该对象;因此,通过调用 keys() __ str __ 创建的视图对象被定义,以便生成的字符串包含dict_keys



寻找自己:

 code>在[1]中:diff_dict = {'easy':0.2,'medium':0.1,'hard':0.05} 

在[2]中:print 3个可能的选择:',diff_dict.keys())
这是3个可能的选择:dict_keys(['medium','hard','easy'])

在[3 ]:diff_dict.keys().__ str __()
Out [3]:dict_keys(['medium','hard','easy'])
/ pre>

请注意,99.9%的时间您不需要直接调用此方法,我只是为了说明事情的工作原理。 >

一般来说,当你想打印一些数据时,你几乎总是想做一些字符串格式化。在这种情况下,一个简单的 str.join 将足够:

 在[4]中:print('这里有3个可能的选择:', ','.join(diff_dict))
这是3种可能的选择:中,硬,容易






所以,回答你的问题:


我可以实现相同的结果吗没有包装新的元素,如diff_keys?


上面显示了一个示例。


为什么diff_dict.keys显示dict。名称?我做错了什么?


因为它的 __ str __ 方法是这样工作的。这是您直接打印对象时必须处理的。


如何打印键或其他元素,如列表,元组,没有字符串引号(')?



与上述#3相同但括号([])


打印它们,以便不调用它们的 __ str __ 。 (基本上不要打印他们。)以任何你喜欢的方式构造一个字符串,制作数据,然后打印。您可以使用字符串格式,以及许多有用的字符串方法


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 :-)

解决方案

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.

这篇关于打印字典键没有字典名称?如何/为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆