说,我有像这样的词干
my_dictionary = {'a':1,'c':5,'b':20,'d':7}
现在,我想用我的dic做到这一点:
if my_dictionary['a'] == 1 and my_dictionary['d'] == 7:
print my_dictionary['c']
这看起来很荒谬,因为我输入了my_dictionary 3次!
那么有什么语法可以让我做这样的事情:
within my_dictionary:
if a == 1 and d == 7:
print c
如果我在我的dic中没有更多的东西(在本例中为b),这实际上会有效:
def f(a,d,c):
if a == 1 and d == 7:
print c
f(**my_dictionary)
答案 0 :(得分:4)
您可以将功能更改为
def f(a,d,c,**args):
if a == 1 and d == 7:
print c
即使你在dict中有其他项目,它也会起作用。
答案 1 :(得分:3)
您可以使用operator.itemgetter
来最小化多个索引:
>>> if operator.itemgetter('a','d')(my_dictionary)==(1,7):
... print operator.itemgetter('c')(my_dictionary)
你可以在一个函数中使用它:
>>> def get_item(*args):
... return operator.itemgetter(*args)(my_dictionary)
...
>>>
>>> if get_item('a','d')==(1,7):
... print get_item('c')
...
5
答案 2 :(得分:2)
回答
所以有任何语法可以让我做这样的事情:
within my_dictionary: if a == 1 and d == 7: print c
您可以将dict子类化,使其具有with
魔术方法。为此,该课程必须具有__enter__
和__exit__
方法。然后,您可以将键导出到with语句的本地范围,并使用exit方法清除它们。
使用this answer我能够创建一个这样做的子类:
import inspect
import ctypes
locals_to_fast = ctypes.pythonapi.PyFrame_LocalsToFast
locals_to_fast.restype = None
locals_to_fast.argtypes = [ctypes.py_object, ctypes.c_int]
class WithDict(dict):
def __enter__(self):
frame = self.get_frame()
for k,v in self.iteritems():
frame.f_locals[str(k)] = v
locals_to_fast(frame, 1)
def __exit__(self, exc_type, exc_value, traceback):
frame = self.get_frame()
for k in self.keys():
del frame.f_locals[str(k)]
def get_frame(self):
return inspect.getouterframes(inspect.currentframe())[2][0]
使用原始示例的测试用例
my_dictionary = WithDict({'a':1,'c':5,'b':20,'d':7})
with my_dictionary:
if a == 1 and d == 7:
print c
打印5
with
语句完成后,变量将被删除