2017-08-17 101 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

相關問題