【发布时间】:2019-07-27 21:22:07
【问题描述】:
我正在处理 Google Python Class 并在字典中使用键值来格式化字符串
hash = {}
hash['word'] = 'garfield'
hash['count'] = 42
s = 'I want %(count)d copies of %(word)s' % hash
# %d for int, %s for string
# 'I want 42 copies of garfield'
这是我的尝试。
my_dict={}
my_dict['1']=50
my_dict['2']=100
s='%(1)d of %(2)d' % my_dict
print s
#Output:
# 50 of 100
#Perfect!
当我使用整数键时会出错。
my_dict={}
my_dict[1]=50
my_dict[2]=100
s='%(1)d of %(2)d' % my_dict
print s
#Output:
#Traceback (most recent call last):
#File "dictformat.py", line 4, in <module>
#s='%(1)d of %(2)d' % my_dict
#KeyError: '1'
字典的形成和打印正确。我看到整数类型的键从here有效
my_dict={}
my_dict[1]=50
my_dict[2]=100
print my_dict
#Output:
#{1: 50, 2: 100}
我了解format string using dict Python3 和Python string formatting: % vs. .format 中提到的python3 中有一个.format 但是,我想知道我的理解有什么问题,或者整数键是否不应该用于字符串格式化?
【问题讨论】:
-
dict 键为字符串时不应使用整数键
标签: python python-3.x python-2.7 dictionary