English 中文(简体)
字典列表值上的 Python s hasattr 总是返回假?
原标题:Python s hasattr on list values of dictionaries always returns false?

我有一本字典,有时会收到不存在密钥的电话, 所以我尝试使用 hasattr getattr 来处理这些案件:

key_string =  foo 
print "current info:", info
print hasattr(info, key_string)
print getattr(info, key_string, [])
if hasattr(info, key_string):
    array = getattr(info, key_string, [])
array.append(integer)
info[key_string] = array
print "current info:", info

第一次使用 integer = 1 运行 :

current info: {}
False
[]
current info: { foo : [1]}

使用 integer = 2 再次运行此代码 :

instance.add_to_info("foo", 2)

current info: { foo : [1]}
False
[]
current info: { foo : [2]}

第一次运行显然成功(

最佳回答

hasattr 不为字典成员测试。 请使用 < code> in 运算符, 或 < code>. has_key 方法 :

>>> example = dict(foo= bar )
>>>  foo  in example
True
>>> example.has_key( foo )
True
>>>  baz  in example
False

但请注意,dict.has_key() 已被折旧,《PEP 8》风格指南建议予以反对,并在Python 3中完全删除。

顺便说一句,你可能会遇到问题,因为你使用一个可变等级变量:

>>> class example(object):
...     foo = dict()
...
>>> A = example()
>>> B = example()
>>> A.foo[ bar ] =  baz 
>>> B.foo
{ bar :  baz }

初始化为 中 :

class State(object):
    info = None

    def __init__(self):
        self.info = {}
问题回答

字典密钥与对象属性不同

thing1 = { a , 123}
hasattr(thing1,  a ) # False
class c: pass
thing2 = c()
thing2.a = 123
hasattr(thing2,  a ) # True

要测试列表/ 字典中的元素, 请在 < code> in 中使用 < code> in 。 要使用默认值, 您可以使用 < code> dict. get :

def add_to_info(self, key_string, integer):
    array = self.info.get(key_string, [])
    array.append(integer)
    self.info[key_string] = array

或者使用默认值 :

from collections import defaultdict
class State(object):
    info = defaultdict(list)

    def add_to_info(self, key_string, integer):
        self.info[key_string].append(integer)

如果您将您的字典转换为点字典, 您可以为此使用 hasattr getattr :

class dotdict(dict):
    """dot.notation access to dictionary attributes"""
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

newdict = dotdict(olddict)

看起来你只需要一条线:

def add_to_info(self, key_string, integer):
    self.info.setdefault(key_string, []).append(integer)

您可以在 dict type 对象上使用.get () 方法。 如果不定义的话, 此方法不会产生关键错误。 另外, 您也可以为对象指定默认值的 makeattr () 。

>> { name :  Me }.get( name1 ,  StackOverflow )
>>  StackOverflow 




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签