【问题标题】:String formatting using integer type key in dictionary returns KeyError in Python 2,works with string type key使用字典中的整数类型键进行字符串格式化在 Python 2 中返回 KeyError,适用于字符串类型键
【发布时间】: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 Python3Python string formatting: % vs. .format 中提到的python3 中有一个.format 但是,我想知道我的理解有什么问题,或者整数键是否不应该用于字符串格式化?

【问题讨论】:

标签: python python-3.x python-2.7 dictionary


【解决方案1】:

查看使用整数键时收到的错误消息KeyError: '1',在字典中搜索的键的类型为str。如果% 的行为符合您的预期,因此寻找整数键但没有找到它,则错误将是KeyError: 1

总而言之,您遇到的问题与% 在字典查找中使用的键的类型有关,即str 而不是int。因此只能使用str 键,Python 中不会发生字符串和整数之间的自动转换。

【讨论】:

    【解决方案2】:

    你可以你f

    my_dict={}
    my_dict[1]=50
    my_dict[2]=100
    s = f"{my_dict[1]} of {my_dict[2]}"
    print(s)
    

    输出:

    50 of 100
    [Finished in 0.2s]
    

    其他方式

    my_dict={}
    my_dict[1]=50
    my_dict[2]=100
    s = "{} of {}".format(*my_dict.values())
    print(s)
    

    输出:

    50 of 100
    [Finished in 0.2s]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 2018-07-16
      • 1970-01-01
      相关资源
      最近更新 更多