格式化dict键:AttributeError:'dict'对象没有属性'keys()'

Nar*_*ann 5 python methods dictionary string-formatting attributeerror

在字符串中格式化dict键的正确方法是什么?

当我这样做:

>>> foo = {'one key': 'one value', 'second key': 'second value'}
>>> "In the middle of a string: {foo.keys()}".format(**locals())
Run Code Online (Sandbox Code Playgroud)

我期待的是:

"In the middle of a string: ['one key', 'second key']"
Run Code Online (Sandbox Code Playgroud)

我得到了什么:

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    "In the middle of a string: {foo.keys()}".format(**locals())
AttributeError: 'dict' object has no attribute 'keys()'
Run Code Online (Sandbox Code Playgroud)

但正如你所看到的,我的dict有键:

>>> foo.keys()
['second key', 'one key']
Run Code Online (Sandbox Code Playgroud)

MSe*_*ert 6

您不能在占位符中调用方法.您可以访问属性和属性甚至索引值 - 但您无法调用方法:

class Fun(object):
    def __init__(self, vals):
        self.vals = vals

    @property
    def keys_prop(self):
        return list(self.vals.keys())

    def keys_meth(self):
        return list(self.vals.keys())
Run Code Online (Sandbox Code Playgroud)

方法示例(失败):

>>> foo = Fun({'one key': 'one value', 'second key': 'second value'})
>>> "In the middle of a string: {foo.keys_meth()}".format(foo=foo)
AttributeError: 'Fun' object has no attribute 'keys_meth()'
Run Code Online (Sandbox Code Playgroud)

有关属性(工作)的示例:

>>> foo = Fun({'one key': 'one value', 'second key': 'second value'})
>>> "In the middle of a string: {foo.keys_prop}".format(foo=foo)
"In the middle of a string: ['one key', 'second key']"
Run Code Online (Sandbox Code Playgroud)

格式化语法清楚地表明您只能访问占位符的属性(a la getattr)或索引(a la __getitem__)(取自"Format String Syntax"):

arg_name后面可以跟任意数量的索引或属性表达式.表单的表达式'.name'选择使用的命名属性getattr(),而表单的表达式'[index]'使用索引查找__getitem__().


使用Python 3.6,您可以使用f-strings轻松完成此操作,您甚至无需传入locals:

>>> foo = {'one key': 'one value', 'second key': 'second value'}
>>> f"In the middle of a string: {foo.keys()}"
"In the middle of a string: dict_keys(['one key', 'second key'])"

>>> foo = {'one key': 'one value', 'second key': 'second value'}
>>> f"In the middle of a string: {list(foo.keys())}"
"In the middle of a string: ['one key', 'second key']"
Run Code Online (Sandbox Code Playgroud)