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

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

问题描述

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

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

当我这样做时:

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

但是正如您所看到的,我的字典有一些键:

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

方法示例(失败):

>>> 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"):

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

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

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

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