Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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字典的基本提取行为吗_Python_Python 3.x_Dictionary - Fatal编程技术网

我们可以改变python字典的基本提取行为吗

我们可以改变python字典的基本提取行为吗,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,字典抽取法 d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} print(d['a']) # prints: 1 要求: print(d['a', 'b']) # should print: [1, 2] 通过子类化dict和修改\uuu getitem\uuuu()方法,这是否可能,如果可能,如何实现?如果您真的想使用子类化,这将很好地完成这项工作: def ret_multiple(dict, *args) for k in args:

字典抽取法

d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(d['a'])  # prints: 1
要求:

print(d['a', 'b'])  # should print: [1, 2]

通过子类化
dict
和修改
\uuu getitem\uuuu()
方法,这是否可能,如果可能,如何实现?

如果您真的想使用子类化,这将很好地完成这项工作:

def ret_multiple(dict, *args)
    for k in args:
        if k in dict:
            ret.append(dict[k])
    return ret

vals = ret_multiple(d, 'a', 'b')   
class CustomDict(dict):
    def __init__(self, dic):
        self.dic = dic

    def __getitem__(self, items):
        values = []
        for item in items:
            values.append(self.dic[item])
        return values if len(values) > 1 else values[0]


d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

new_d = CustomDict(d)

print(new_d['a'])
print(new_d['a', 'b'])
print(new_d['a', 'b', 'c'])
print(new_d['a', 'c', 'd'])
输出:

1
[1, 2]
[1, 2, 3]
[1, 3, 4]
说明:

new\u d
CustomDict
类的一个对象,它将始终回退到父类的方法(以便在对象上循环以及您可能希望对字典执行的其他操作),除非调用其中一个重写方法(init,getitem)


因此,当使用
new\u d['a','b']
时,将调用重写的
\u getitem\u
方法。重写方法使用
self.dic
(这是一个普通字典)的
\uuu getitem\uuu
来实际访问每个给定键的字典值。

也可以始终将此需求作为函数编写,而不是与完全正常的数据类型混淆。类似于
fetch(dict,key\u list)
是的,这是可能的。你试过了吗,你有没有被卡住过?我建议不要对内置函数进行子类化并改变它们的行为,当你在看似普通的字典中使用虚构的语法时,这会让其他人非常困惑。最好只创建一个@paritossingh建议的函数。@ruohola:子类化很好,只要不替换所有
dict
对象。大量优秀的Python项目子类
dict
,包括标准库(
collections.defaultdict
collections.Counter
都是这样的子类)。幸运的是,Python不是Ruby。@MartijnPieters非常正确,这只是尖叫OP希望能够在任何随机字典中做到这一点……为什么要对
键使用可变的默认值呢?至少让它成为一个
()
元组,这样它就不会被意外修改。你可以使用一个
*keys
catch all参数,这样就可以支持
ret_multiple(d,'a,'b')
。Idk dude我刚刚写了这个超快速的。我不是那样的smart@amchugh89但是,您可以初始化
ret
,而不是使用内置的
dict
并在函数定义行上添加
。也许superfast太快了。尽管这可能回答了这个问题,但是没有对代码的解释。请更新您的答案,解释您正在做的事情。谢谢