格式化dict键:AttributeError:'dict'对象没有属性'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']"

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

arg_name后面可以跟任意数量的索引或属性表达式。表单的表达式'.name'使用来选择命名属性getattr(),而表单的表达式'[index]'使用来进行索引查找__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']"

解决方法

格式化字符串中的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']