繁体   English   中英

为什么字典键和值在是字符串时可以解包为元组?

[英]Why dictionary keys and values can be unpacked as a tuple when they are a string?

我有这个代码:

my_dict = {"one":"AAA", "two":"BBB", "thr":"CCC"}
for a, b, c in my_dict.keys():
    print(a, b, c)
print("-----")   
for x, y, z in my_dict.values():
    print(x, y, z)

并在运行时返回低于输出。

o n e
t w o
t h r
-----
A A A
B B B
C C C

有人可以解释为什么当键和值是字符串类型时它能够将键和值解包为元组吗?

我知道my_dict.items()可以解包为 (a, b) 类型的元组,因为my_dict.items()返回一个元组。 但是为什么这里返回类型是字符串呢?

这与字典本身无关。

这完全有效,因为字符串是“不可压缩的”,因为它们是可迭代的。

您的代码工作的原因与以下工作的原因相同:

a, b, c = 'abc'
print(a, b, c)
# a b c

请注意,如果任何字符串碰巧短于或长于 3 个字符,您的示例(以及我示例中的代码)将会中断:

a, b, c = 'abcd'
ValueError: too many values to unpack (expected 3)

a, b, c = 'ab'
ValueError: not enough values to unpack (expected 3, got 2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM