向字典添加多个键(python)
我用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
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}