格式化字典键:AttributeError: 'dict' 对象没有属性 'keys()' [英] Formatting dict keys: AttributeError: 'dict' object has no attribute 'keys()'

查看:22
本文介绍了格式化字典键:AttributeError: 'dict' 对象没有属性 'keys()'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

当我这样做时:

<预><代码>>>>foo = {'one key': 'one value', 'second key': 'second value'}>>>"在字符串中间:{foo.keys()}".format(**locals())

我的期望:

"在字符串中间:['one key', 'second key']"

我得到了什么:

回溯(最近一次调用最后一次):文件<pyshell#4>",第 1 行,在 <module> 中"在字符串中间:{foo.keys()}".format(**locals())AttributeError: 'dict' 对象没有属性 'keys()'

但是正如你所看到的,我的字典有键:

<预><代码>>>>foo.keys()['第二键','一键']

解决方案

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

class Fun(object):def __init__(self, vals):self.vals = vals@财产def keys_prop(self):返回列表(self.vals.keys())def keys_meth(self):返回列表(self.vals.keys())

方法示例(失败):

<预><代码>>>>foo = Fun({'one key': 'one value', 'second key': 'second value'})>>>"在字符串中间:{foo.keys_meth()}".format(foo=foo)AttributeError: 'Fun' 对象没有属性 'keys_meth()'

属性示例(工作):

<预><代码>>>>foo = Fun({'one key': 'one value', 'second key': 'second value'})>>>"在字符串中间:{foo.keys_prop}".format(foo=foo)在字符串中间:['one key', 'second key']"

格式化语法清楚地表明您只能访问属性(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"在字符串中间:{foo.keys()}"在字符串中间:dict_keys(['one key', 'second key'])">>>foo = {'one key': 'one value', 'second key': 'second value'}>>>f"在字符串中间:{list(foo.keys())}"在字符串中间:['one key', 'second key']"

What is the proper way to format dict keys in string?

When I do this:

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

What I expect:

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

What I get:

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

But as you can see, my dict has keys:

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

解决方案

You can't call methods in the placeholders. You can access properties and attributes and even index the value - but you can't call methods:

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

Example with method (failing):

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

Example with property (working):

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

The formatting syntax makes it clear that you can only access attributes (a la getattr) or index (a la __getitem__) the placeholders (taken from "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__().


With Python 3.6 you can easily do this with f-strings, you don't even have to pass in 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']"

这篇关于格式化字典键:AttributeError: 'dict' 对象没有属性 'keys()'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆