2017-08-17 104 views
3

在字符串中格式化字典键的正确方法是什么?格式化字典键:AttributeError:'字典'对象没有属性'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'] 
+0

在python上的哪个版本? 2或3? – Kosch

+1

[相关,可能dup](https://stackoverflow.com/questions/19796123/python-string-format-calling-a-function) – Wondercricket

+0

@Kosh Python 2.7 – Narann

回答

3

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

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-串做到这一点,你甚至不必在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']" 
+1

是的,我明白了。我会删除我之前的评论。几分钟后这一个。 –

0
"In the middle of a string: {}".format(list(foo.keys())) 
+0

请添加一个什么的描述,为什么?如何?你的代码是。没有解释就能理解的人也不需要代码。 – jpaugh

0
"In the middle of a string: {}".format([k for k in foo]) 
+0

你应该尝试解释你的答案,而不是仅仅留下一行没有上下文的代码,它会帮助这个提问者和未来的访问者进入页面 – Wolfie

相关问题