打印字典名称 [英] print names of dictionaries
问题描述
还是新的。学习属性和功能等等。
对不起,如果这是显而易见的,但是如果我为某些
词典定义一个函数,我怎么能只打印字典的名称?
例如假设应用程序,目录,网站是模块中定义的词典,
如何在与其他人做其他事情之前打印他们的名字。
def printdict( dicts = [app,dirs,sites]):
dict in dicts:
打印???
谢谢
rpd
Still new. Learning attributes and functions and so on.
Sorry if this is obvious, but if I''m defining a function for some
dictionaries, how can I print just the names of the dictionaries?
E.g. assuming apps, dirs, sites are dictionaries defined in the module,
how can I print just their names before doing other things with them.
def printdict(dicts=[apps, dirs, sites]):
for dict in dicts:
print ???
Thank you
rpd
推荐答案
BartlebyScrivener写道:
BartlebyScrivener wrote:
仍然新。学习属性和功能等等。
很抱歉,如果这很明显,但如果我正在为某些词典定义一个函数,我怎样才能打印出词典的名称?
Still new. Learning attributes and functions and so on.
Sorry if this is obvious, but if I''m defining a function for some
dictionaries, how can I print just the names of the dictionaries?
简答:你不能。
http://pyfaq.infogami.com/how-can-my...e-of-an-object
....
Jay Graves
Short answer: You can''t.
http://pyfaq.infogami.com/how-can-my...e-of-an-object
....
Jay Graves
这里这可能是你想做的事情:
Here''s an OO way that may do what you want:
class MyD(dict):
... .def __init __(self,dic,rep):
.... dict .__ init __(self,dic)
.... self.rep = rep
.... def __repr __(自我):
....返回self.rep
.... apps = MyD({' '阿尔法' ':1', '测试' ':2}', '应用程序'')<无线电通信/> apps
apps apps.keys()
class MyD(dict): .... def __init__(self,dic,rep):
.... dict.__init__(self,dic)
.... self.rep = rep
.... def __repr__(self):
.... return self.rep
.... apps = MyD({''alpha'':1,''beta'':2},''apps'')
apps apps apps.keys()
[''alpha'',''beta'']
当然,最简单的方法就是使用元组(字典,字符串)。
作为旁注,因为dict是内置类型,功能,它可能不是
将它用作循环变量的好方式。
THN
[''alpha'', ''beta'']
Of course, the easiest way is just to use a tuple (dict,string).
As a side note, since dict is a builtin type and function, it might not
be good style to use it as a loop variable.
THN
哇,
这是值得深思的。谢谢。
我看到他们对改变方法的意思。我只需在每个字典中输入一个密钥,每个字典名称为er,名称及其名称值。
谢谢!
rick
Wow,
That''s food for thought. Thanks.
I see what they mean about change of approach. I''ll just stick a key in
each dictionary called, er, name with its name value.
Thank you!
rick
这篇关于打印字典名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!