标签: dictionary-missing

如何制作一个python字典,返回字典中缺少键的键,而不是引发KeyError?

我想创建一个python字典,它返回字典中缺少键的键值.

用法示例:

dic = smart_dict()
dic['a'] = 'one a'
print(dic['a'])
# >>> one a
print(dic['b'])
# >>> b
Run Code Online (Sandbox Code Playgroud)

python dictionary data-structures dictionary-missing

54
推荐指数
5
解决办法
2万
查看次数

宽容的字典

我想知道如何创建宽容字典(如果引发KeyError则返回默认值).

在下面的代码示例中,我将得到一个KeyError; 例如

a = {'one':1,'two':2}
print a['three']
Run Code Online (Sandbox Code Playgroud)

为了不得到一个我将1.必须捕获异常或使用获取.

我不想用我的字典那样做...

python dictionary defaultdict dictionary-missing

9
推荐指数
3
解决办法
677
查看次数

functools.wrapper - AttributeError: 'type' 对象的属性 '__doc__' 不可写

在执行下面的代码时,我得到AttributeError: attribute '__doc__' of 'type' objects is not writable.

from functools import wraps

def memoize(f):
    """ Memoization decorator for functions taking one or more arguments.
        Saves repeated api calls for a given value, by caching it.
    """
    @wraps(f)
    class memodict(dict):
       """memodict"""
       def __init__(self, f):
           self.f = f
       def __call__(self, *args):
           return self[args]
       def __missing__(self, key):
           ret = self[key] = self.f(*key)
           return ret
     return memodict(f)

@memoize
def a():
    """blah"""
    pass
Run Code Online (Sandbox Code Playgroud)

追溯:

from functools import wraps

def memoize(f):
    """ Memoization …
Run Code Online (Sandbox Code Playgroud)

decorator python-2.7 functools dictionary-missing

5
推荐指数
1
解决办法
6264
查看次数

如何使用defaultdict行为扩展OrderedDict

我有一份命令字典。我想将所有这些组合在一起,然后按每个中的fruit属性对其进行排序。我一直在通过下面的代码使用defaultdict对它们进行组合和排序。

super_dict_apple = defaultdict(list)
super_dict_orange = defaultdict(list)
super_dict_no_fruit = defaultdict(list)


for d in dict:
        if 'fruit' not in d:
            for k, v in d.iteritems():
                super_dict_no_fruit[k].append(v)
        elif d['fruit'] == 'Apple':
            for k, v in d.iteritems():
                super_dict_apple[k].append(v)
        elif d['fruit'] == 'orange':
            for k, v in d.iteritems():
                super_dict_orange[k].append(v)  
Run Code Online (Sandbox Code Playgroud)

这样我得到了一个键和所有相关的值,但是我失去了原始顺序。因此,我尝试使用orderDict来执行此操作,但是我无法使其正常工作,以下是我尝试过的操作。

from collections import OrderedDict

order_dict_no_fruit = OrderedDict()
order_dict_apple = OrderedDict()
order_dict_orange = OrderedDict()

for d in dict:
        if 'fruit' not in d:
            for k, v in d.iteritems():
                order_dict_no_fruit[k].append(v)
        elif d['fruit'] == 'Apple':
            for k, …
Run Code Online (Sandbox Code Playgroud)

python ordereddictionary data-structures defaultdict dictionary-missing

3
推荐指数
1
解决办法
1155
查看次数

Python:如何将函数分配给Object属性?

基本上这开始于我在尝试查找索引是否存在于dict中时遇到的问题:

if collection[ key ]: # if exist
    #do this
else: # if no exist
    #do this
Run Code Online (Sandbox Code Playgroud)

但是当索引确实不存在时,它会抛出一个KeyError.所以,阅读Python文档.如果定义了missing(),则不会抛出KeyError.

collection = {}
def collection.__missing__():
    return false
Run Code Online (Sandbox Code Playgroud)

终端上面的代码给了我:

ghelo@ghelo-Ubuntu:~/Music$ python __arrange__.py
  File "__arrange__.py", line 16
    def allArts.__missing__():
               ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

那么,如何正确地做到这一点?顺便说一下,我需要在这上面使用Python 2.7.在Python 3上运行时有区别吗?

python function python-2.7 dictionary-missing

1
推荐指数
1
解决办法
150
查看次数

Python 2 __missing__方法

我写了一个非常简单的程序来子类化字典.我想__missing__在python中尝试该方法.经过一些研究后我发现在Python 2中可用defaultdict.(在python 3中我们使用collections.UserDict虽然..)如果找不到密钥,则__getitem__负责调用该__missing__方法.

当我__getitem__在下面的程序中实现时,我得到一个关键错误,但是当我没有它实现时,我得到了所需的值.

import collections
class DictSubclass(collections.defaultdict):

    def __init__(self,dic):
        if dic is None:
            self.data = None
        else:
            self.data = dic

    def __setitem__(self,key,value):
        self.data[key] = value

    ########################
    def __getitem__(self,key):
        return self.data[key]
    ########################

    def __missing__(self,key):
        self.data[key] = None

dic = {'a':4,'b':10}
d1 = DictSubclass(dic)
d2 = DictSubclass(None)    
print  d1[2]
Run Code Online (Sandbox Code Playgroud)

我认为我需要实施,__getitem__因为它负责呼叫__missing__.据我所知,defaultdict的类定义有一个__getitem__方法.但即便如此,说我想写自己的__getitem__,我该怎么做?

python dictionary python-2.x dictionary-missing

1
推荐指数
1
解决办法
5676
查看次数