gpt4 book ai didi

python - 格式化字典键 : AttributeError: 'dict' object has no attribute 'keys()'

转载 作者:太空狗 更新时间:2023-10-30 00:59:03 29 4
gpt4 key购买 nike

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

最佳答案

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

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 la getattr)或索引(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-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']"

关于python - 格式化字典键 : AttributeError: 'dict' object has no attribute 'keys()' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45736050/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com