Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何重写python dict以获取默认值_Python_Dictionary - Fatal编程技术网

如何重写python dict以获取默认值

如何重写python dict以获取默认值,python,dictionary,Python,Dictionary,我想重写Python的字典访问机制“getitem”,以便能够返回默认值 我正在寻找的功能类似于 a = dict() a.setdefault_value(None) print a[100] #this would return none 有什么提示吗 谢谢已经有了: 从Python2.6开始有一个新的版本。构造函数接受一个函数,当找不到值时将调用该函数。这比不返回任何值提供了更多的灵活性 from collections import defaultdict a = defaultdi

我想重写Python的字典访问机制“getitem”,以便能够返回默认值

我正在寻找的功能类似于

a = dict()
a.setdefault_value(None)
print a[100] #this would return none
有什么提示吗

谢谢

已经有了:

从Python2.6开始有一个新的版本。构造函数接受一个函数,当找不到值时将调用该函数。这比不返回任何值提供了更多的灵活性

from collections import defaultdict

a = defaultdict(lambda: None)
print a[100] #gives None
lambda
只是定义一个没有名称的单行函数的快速方法。此代码等效于:

def nonegetter():
    return None

a = defaultdict(nonegetter)
print a[100] #gives None
这是一个非常有用的模式,它提供了一个显示每个唯一对象计数的哈希。使用普通的dict,您需要特殊的情况来避免键错误

counts = defaultdict(int)
for obj in mylist:
   counts[obj] += 1

使用
defaultdict
()

其中,
defaultdict
构造函数的参数是一个返回默认值的函数

请注意,如果访问未设置的条目,它实际上会将其设置为默认值:

>>> print a[100]
None
>>> a
defaultdict(<function <lambda> at 0x38faf0>, {100: None})
>打印[100]
没有一个
>>>a
defaultdict(,{100:None})
如果确实不想使用defaultdict内置,则需要定义自己的dict子类,如下所示:

class MyDefaultDict(dict):
    def setdefault_value(self, default):
        self.__default = default
    def __getitem__(self, key):
        try:
            return self[key]
        except IndexError:
            return self.__default

我没有意识到默认dict,这可能是最好的方法。如果你出于某种原因反对,我以前就为此写过小包装函数。具有稍微不同的功能,可能对您有利,也可能对您不利

def makeDictGet(d, defaultVal):
    return lambda key: d[key] if key in dict else defaultVal
使用它

>>> d1 = {'a':1,'b':2}
>>> d1Get = makeDictGet(d1, 0)
>>> d1Get('a')
1
>>> d1Get(5)
0
>>> d1['newAddition'] = 'justAddedThisOne'    #changing dict after the fact is fine
>>> d1Get('newAddition')
'justAddedThisOne'
>>> del d1['a']
>>> d1Get('a')
0
>>> d1GetDefaultNone = makeDictGet(d1, None)   #having more than one such function is fine
>>> print d1GetDefaultNone('notpresent')
None
>>> d1Get('notpresent')
0
>>> f = makeDictGet({'k1':'val1','pi':3.14,'e':2.718},False) #just put new dict as arg if youre ok with being unable to change it or access directly
>>> f('e')
2.718
>>> f('bad')
False

另一种可能是使用a.get(100,无)是的,我知道,谢谢。但是在我的代码中到处都是这样是很难看的。你想让它将缺少的键设置为None,还是简单地返回None而不是引发KeyError?你的lambda应该是
lambda:None
,否则你会得到
TypeError:()正好取1个参数(给定0)
@bukzor,史蒂文:你是对的,我可能在你打字的时候修复了它。我如何避免使用defaultdict???@webDevelSouth:你为什么要避免使用defaultdict?我猜他正在使用它作为进入python OOP的垫脚石。我把它放在了一个单独的答案中。我想我可以在脚本的顶部将MyclassDefaultDict作为dict导入,然后我可以将MyclassDefaultDict作为“dict”导入-我说得对吗?嗯,你可以,但不应该。首先,对于使用花括号定义的dict,它仍然无法实现
{“foo”:1}
仍然是Python
dict
,即使您已将
dict
重新定义为其他类。另一方面,如果维护您的代码的人(包括您自己在六个月内)看到
dict
,他们会认为这是常规的Python dict类型。
def makeDictGet(d, defaultVal):
    return lambda key: d[key] if key in dict else defaultVal
>>> d1 = {'a':1,'b':2}
>>> d1Get = makeDictGet(d1, 0)
>>> d1Get('a')
1
>>> d1Get(5)
0
>>> d1['newAddition'] = 'justAddedThisOne'    #changing dict after the fact is fine
>>> d1Get('newAddition')
'justAddedThisOne'
>>> del d1['a']
>>> d1Get('a')
0
>>> d1GetDefaultNone = makeDictGet(d1, None)   #having more than one such function is fine
>>> print d1GetDefaultNone('notpresent')
None
>>> d1Get('notpresent')
0
>>> f = makeDictGet({'k1':'val1','pi':3.14,'e':2.718},False) #just put new dict as arg if youre ok with being unable to change it or access directly
>>> f('e')
2.718
>>> f('bad')
False