向字典添加多个键(python)

2024-09-24 22:30:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python创建字典:d = dict.fromkeys(['one', 'two', 'three'], 1)

但是我不知道,我怎么能把多个键加到字典里 ['one2','two2','three2']->;2

因此,结果字典应该是:

['one'、'two'、'three']->;1 ['one2','two2','three2']->;2


Tags: gt字典onedictthreetwofromkeysone2
1条回答
网友
1楼 · 发布于 2024-09-24 22:30:15

一种方法是使用另一个dict.fromkeys字典的结果进行更新:

d = dict.fromkeys(['one', 'two', 'three'], 1)
d.update(dict.fromkeys( ['one2', 'two2', 'three2'] , 2))

结果:

^{pr2}$

如果你有更多的数据像这样更新,可能会很乏味。在这种情况下,创建一个包含键/值的元组列表,并使用dict comprehension将其“展平”:

kv = [(['one', 'two', 'three'], 1),(['one2', 'two2', 'three2'] , 2)]

d = {k:v for kl,v in kv for k in kl}

相关问题 更多 >