在字符串中格式化字典鍵的正確方法是什麼?格式化字典鍵: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']
在python上的哪個版本? 2或3? – Kosch
[相關,可能dup](https://stackoverflow.com/questions/19796123/python-string-format-calling-a-function) – Wondercricket
@Kosh Python 2.7 – Narann