设置字典键的格式:属性错误:'dict'对象没有属性'keys()'



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

当我这样做时:

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

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

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

格式语法清楚地表明,您只能访问属性(getattr(或索引(__getitem__(占位符(取自"格式字符串语法"(:

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


使用 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(list(foo.keys()))
"In the middle of a string: {}".format([k for k in foo])

正如上面其他人所说,您不能以自己喜欢的方式进行操作,以下是遵循调用函数的python字符串格式的其他信息

最新更新