在 python 中将数组转换为散列

Converting an array to hash in python

正在尝试将列表转换为字典,但无法获得预期的输出

p = {}
a = ["s","l","y"]
for s in a:
    p["size"] = s

print(p)

输出:

{'size': 'y'}

但我期待这样的输出

{'size': 's','size': 'l','size': 'y'}

我如何在 python

中实现这一点

您无法实现您的目标,因为您使用的是字典,而且字典中的每个键都是唯一的。也许您想改用列表:

p = []
a = ['s', 'l', 'y']
for s in a:
    p.append(('size',  s))

print(p)

输出:

[('size', 's'), ('size', 'l'), ('size', 'y')]

字典中不能有多个相同的键,因此可以使用字典列表。一个简单的列表理解应该可以解决问题。

p = [{'size': a_size} for a_size in a]

结果:

[{'size': 's'}, {'size': 'l'}, {'size': 'y'}]

下面的代码应该是一个干净的解决方案。

p = {}
a = ["s", "l","y"]
for s in a:
    if s == "s":
        p["small-size"] = s
    elif s == "l":
        p["large-size"] = s
    else:
        p["youth-size"] = s

print(p)

输出如下:

{'small-size': 's', 'large-size': 'l', 'youth-size': 'y'}