格式化dict keys:attributeRor:“dict”对象没有属性“keys()”

2024-03-28 08:52:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

当我这样做时:

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

我期望的是:

"In the middle of a string: ['one key', 'second key']"

我得到的是:

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()'

但正如你所见,我的字典有钥匙:

>>> foo.keys()
['second key', 'one key']

Tags: ofthekey字符串informatmiddlestring
3条回答
"In the middle of a string: {}".format(list(foo.keys()))

不能在占位符中调用方法。您可以访问属性和属性,甚至为值编制索引,但不能调用方法:

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())

方法示例(失败):

>>> 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()'

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

>>> 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']"

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

The arg_name can be followed by any number of index or attribute expressions. An expression of the form '.name' selects the named attribute using getattr(), while an expression of the form '[index]' does an index lookup using __getitem__().


使用Python 3.6,您可以使用f字符串轻松完成此操作,甚至不必传入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']"
"In the middle of a string: {}".format([k for k in foo])

相关问题 更多 >