Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
向字典添加多个键(python)_Python_Dictionary_Key - Fatal编程技术网

向字典添加多个键(python)

向字典添加多个键(python),python,dictionary,key,Python,Dictionary,Key,我用python创建字典:d=dict.fromkeys(['one','two','three',]1) 但是我不知道,我怎样才能像这样把多个键添加到这本字典中呢 ['one2','two2','three2']->2 因此,结果字典应为: ['1','2','3']->1 ['one2','two2','three2']->2一种方法是用另一种方法的结果更新dict.fromkeys字典: d = dict.fromkeys(['one', 'two', 'three'], 1) d.upd

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

但是我不知道,我怎样才能像这样把多个键添加到这本字典中呢 ['one2','two2','three2']->2

因此,结果字典应为:

['1','2','3']->1
['one2','two2','three2']->2

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

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

{'one': 1, 'two': 1, 'two2': 2, 'three2': 2, 'three': 1, 'one2': 2}
如果您有更多的数据要这样更新,可能会很乏味。在这种情况下,制作一个包含键/值的元组列表,并使用dict comprehension将其“展平”:

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

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

您的问题有点不清楚,能否将输出格式化为-
{'one':1,'two':1,'three':1}