Python's hasattr on list values of dictionaries always returns false?

后端 未结 5 1047
离开以前
离开以前 2020-12-15 03:53

I have a dictionary that sometimes receives calls for non-existent keys, so I try and use hasattr and getattr to handle these cases:



        
相关标签:
5条回答
  • 2020-12-15 04:02

    A dictionary key is not the same as an object attribute

    thing1 = {'a', 123}
    hasattr(thing1, 'a') # False
    class c: pass
    thing2 = c()
    thing2.a = 123
    hasattr(thing2, 'a') # True
    
    0 讨论(0)
  • 2020-12-15 04:03

    You may use .get() method on a dict type object. This method doesnt raise a key error if isnt defined. Also, as the getattr() for objects you may specify on it a default value.

    >> {'name': 'Me'}.get('name1', 'StackOverflow')
    >> 'StackOverflow'
    
    0 讨论(0)
  • 2020-12-15 04:14

    Looks like all you need is one line:

    def add_to_info(self, key_string, integer):
        self.info.setdefault(key_string, []).append(integer)
    
    0 讨论(0)
  • 2020-12-15 04:19

    To test for elements in a list/dictionary, use in. To use defaults, you can use dict.get:

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

    Or use defaultdict:

    from collections import defaultdict
    class State(object):
        info = defaultdict(list)
    
        def add_to_info(self, key_string, integer):
            self.info[key_string].append(integer)
    
    0 讨论(0)
  • 2020-12-15 04:21

    hasattr does not test for members of a dictionary. Use the in operator instead, or the .has_key method:

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

    But note that dict.has_key() has been deprecated, is recommended against by the PEP 8 style guide and has been removed altogether in Python 3.

    Incidentally, you'll run into problems by using a mutable class variable:

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

    Initialize it in your __init__ instead:

    class State(object):
        info = None
    
        def __init__(self):
            self.info = {}
    
    0 讨论(0)
提交回复
热议问题