0
Follow
4
View

Python - How to avoid refer multiple names to one dict

dapi890621 注册会员
6 days ago

Consider

>>> defaults = {'foo': 'bar', 'bee': 'blah'}
>>> actual = dict(defaults)
>>> actual['foo'] = 'BAZ'
>>> defaults
{'foo': 'bar', 'bee': 'blah'}
>>> actual
{'foo': 'BAZ', 'bee': 'blah'}

The trick is actual = dict(defaults). This way actual can be changed without affecting defaults.

If your dicts have sub-objects, consider deepcopy or json.dumps/loads to make a deep copy:

>>> myDict = {'s1':1,  's2':{'b1':2, 'b2':3}}
>>>
>>> from copy import deepcopy
>>>
>>> myDict2 = deepcopy(myDict)
>>>
>>> myDict2['s2']['b1'] = 99
>>>
>>> myDict
{'s1': 1, 's2': {'b1': 2, 'b2': 3}}
>>> myDict2
{'s1': 1, 's2': {'b1': 99, 'b2': 3}}
daiyao225 注册会员
6 days ago

I would use defaultSettings.copy() or dict(defaultSettings) to create a copy of the dict

About the Author

Question Info

Publish Time
6 days ago
Update Time
6 days ago

Related Question

cx_Oracle python删除多进程环境中的语句

cocos creator的js问题

带有列表的Python索引嵌套字典

Python编写程序,输出各位数字之和等于14的所有3位数。

AutoMapper实体到Dto的转换:映射类型错误

Python字符串格式来控制字符串的大小?

Python:清除/重置' @lru_cache ' functool缓存每个pytest测试用例不受干扰的模拟

libtorch torch::jit::load错误

Python怎么一个进程生产,多个进程队列处理生产出来的内容呢?

简单随机块模型(语言-python)