如何从 Python 中的函数内部的字典中调用键?

How to call keys from a dictionary which is inside a function in Python?

我有以下代码:

def all_dsc(x):
    dict={'a':x+2,'b':x-2}
    return dict

我想在函数之外专门调用此词典中的键。 smthn 喜欢:

all_dsc.dict.keys()

最好的方法是什么?

您不能从函数外部访问函数中的局部变量。您所能做的就是通过 调用 函数来 return 字典对象,您已经这样做了。

调用函数,然后将调用表达式的结果当作字典即可:

all_dsc(42).keys()

演示:

>>> all_dsc(42)
{'a': 44, 'b': 40}
>>> all_dsc(42).keys()
['a', 'b']

请注意,如果可以避免的话,您真的不应该使用 built-in 类型的名称作为变量。 dict 是 built-in 类型,所以在这里尝试使用不同的名称:

def all_dsc(x):
    mapping = {'a': x + 2, 'b': x - 2}
    return mapping

甚至完全避免创建本地,因为这在这里并不重要:

def all_dsc(x):
    return {'a': x + 2, 'b': x - 2}