如何复制0值的字典

时间:2018-01-16 09:45:13

标签: python dictionary

我能做什么:

dict1 = {'key1':0, 'key2':10, 'key3':110}
dict2 = dict(dict1)
for key in dict2:
    dict2[key] = 0

print(dict2) # {'key1':0, 'key2':0, 'key3':0}

有一种简单的方法吗?

3 个答案:

答案 0 :(得分:5)

最简单,使用dict comprehension

>>> {k:0 for k in dict1}

#driver值:

IN : dict1 = {'key1':0, 'key2':10, 'key3':110}
OUT : {'key1':0, 'key2':0, 'key3':0}

答案 1 :(得分:5)

是。使用dict.fromkeys

>>> dict1 = {'key1':0, 'key2':10, 'key3':110}
>>> dict.fromkeys(dict1, 0)
{'key1': 0, 'key2': 0, 'key3': 0}

但要注意,如果你的fill-value是一个可变对象,这意味着每个值都是该可变对象的相同实例,例如:

>>> new_dict = dict.fromkeys(dict1, [])
>>> new_dict
{'key1': [], 'key2': [], 'key3': []}
>>> new_dict['key1'].append('foo')
>>> new_dict
{'key1': ['foo'], 'key2': ['foo'], 'key3': ['foo']}

答案 2 :(得分:1)

dict1 = {'key1':0, 'key2':10, 'key3':110}
dict2 = dict((i,0) for i in dict1)

<强>结果

{'key3': 0, 'key2': 0, 'key1': 0}