【问题标题】:Python: Unpacking dictionary with integer keys?Python:用整数键解包字典?
【发布时间】:2020-10-23 13:15:39
【问题描述】:

对于字典如下:

my_dict={'name':'Stack', 'age':11}
print('Name is {name} and age is {age}.'.format(**my_dict))
#output# Name is Stack and age is 11

但是,如果字典中的键是整数,我应该如何解包字典,例如:

new_dict={1:'Stack', 2:'over', 3:'flow'}
print('1 is {1} and 2 is {2} and 3 is {3}'.format(**new_dict))
#output error# tuple index out of range

在这种情况下,我怎样才能得到如下结果:

1 is Stack and 2 is over and 3 is flow

我知道可以通过许多其他方式做到这一点,但是否可以在第一个示例中使用相同的策略。谢谢。

【问题讨论】:

  • 数字用于位置索引。 IE。你可以(但可能不应该)做print('1 is {0} and 2 is {1} and 3 is {2}'.format(*new_dict)) 或者最好是print(f'1 is {new_dict[1]} and 2 is {new_dict[2]} and 3 is {new_dict[3]}')
  • 谢谢您的解释

标签: python dictionary integer string-formatting unpack


【解决方案1】:

dict.values()可以用,*只能用一个:

new_dict={1:'Stack', 2:'over', 3:'flow'}

print('1 is {} and 2 is {} and 3 is {}'.format(*new_dict.values()))

输出:

1 is Stack and 2 is over and 3 is flow

您收到错误的原因是,您知道在 f 字符串中,花括号中的内容是在运行时评估的。

因此,将数字作为键会让 python 认为键是常规整数。

更新:

new_dict={1:'Stack', 2:'over', 3:'flow'}

print(f'3 is {new_dict[3]} and 1 is {new_dict[1]} and 2 is {new_dict[2]}')

输出:

3 is flow and 1 is Stack and 2 is over

【讨论】:

  • 谢谢。但是,如果我想要结果为“1 是堆栈,3 处于流中”,意味着不列出所有元素或更改顺序,例如“3 是流,1 是堆栈,2 结束”
【解决方案2】:
my_dict={'name':'Stack', 'age':11, 1:'Stack', 2:'over', 3:'flow'}

for k, v in my_dict.items():
    if k == list(my_dict.keys())[-1]:
        print(k, 'is', v)
    else:
        print(k, 'is', v, 'and ', end='')

它输出:

name is Stack and age is 11 and 1 is Stack and 2 is over and 3 is flow

【讨论】:

    【解决方案3】:

    你不能这样做解包。你需要的是别的东西。

    ** 在函数调用中将 dict 解包为关键字参数,关键字参数名称始终是字符串。 int 1 不是有效的关键字参数名称。即使是这样,或者如果您将 dict 键转换为字符串,str.format 也不会寻找这样的关键字参数。

    {1}{2} 等在 format 中查找位置参数,而不是关键字参数。否 ** 解包会产生位置参数。此外,由于它们是有位置的,如果从 1 开始,则需要在位置 0 有一个虚拟参数,以便其余参数可以放在正确的位置。

    如果你真的想用一个看起来像这样的 dict 和格式字符串来做到这一点,可能最简单的方法是通过 string.Formatter 子类并覆盖 get_value

    import string
    
    class IntDictFormatter(string.Formatter):
        def get_value(self, key, args, kwargs):
            return kwargs[key]
    
    format_string = '1 is {1} and 2 is {2} and 3 is {3}'
    
    value_dict = {1:'Stack', 2:'over', 3:'flow'}
    
    print(IntDictFormatter().vformat(format_string, (), value_dict))
    

    【讨论】:

    • 好吧,下面是执行此操作的代码。有什么问题?
    • @ShivamJha:你是在谈论你的答案吗?您的回答也没有进行拆包。它也没有推广到其他格式字符串,if k == list(my_dict.keys())[-1] 确实效率低下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 2017-11-26
    • 1970-01-01
    • 2011-03-09
    • 2012-11-02
    • 2021-10-25
    • 1970-01-01
    相关资源
    最近更新 更多