Inserting values into a dictionary without just creating a reference
is there a way to insert a dictionary into another dictionary without just creating a reference to the dictionary.e.g
dict_a = {}
dict_b = {}
dict_开发者_开发知识库a.insert(key, value)
this would prevent the problems that come with
dict_a["somekey"] = dict_b
You could use copy.deepcopy on b:
>>> a = {'a':[1,2,3]}
>>> b = {'b':[4,5,6]}
>>> a['c'] = copy.deepcopy(b)
>>> a
{'a': [1, 2, 3], 'c': {'b': [4, 5, 6]}}
>>> b
{'b': [4, 5, 6]}
>>> b['b'].append(7)
>>> b
{'b': [4, 5, 6, 7]}
>>> a
{'a': [1, 2, 3], 'c': {'b': [4, 5, 6]}}
Using update or copy as above will perform a shallow copy.
Yes.
dict_a.update(dict_b)
This will insert all the keys/values from dict_b
into dict_a
(note: this is in-place and returns None
)
I think you may be meaning update?
>>> dict_a = {1: 'a'}
>>> dict_b = {2: 'b'}
>>> dict_a.update(dict_b)
>>> dict_a
{1: 'a', 2: 'b'}
Or you mean that you want a copy?
>>> from copy import copy
>>> dict_a = {1: 'a'}
>>> dict_b = {2: 'b'}
>>> dict_a['dict'] = copy(dict_b)
>>> dict_a
{1: 'a', 'dict': {2: 'b'}}
EDIT: this answer is better. You should use copy.deepcopy
or else you'll get references to objects stored in the dictionary-to-be-copied in the copied dictionary.
Original answer below:
You need to explicitly create a copy of the second dictionary, and set that as the value in the original dictionary.
dict_a["somekey"] = dict_b.copy()
When you copy
a dictionary, it does exactly what's on the tin, it creates a brand new copy of the original dictionary.
You need to make a copy:
dict_a["dsomekey"] = dict_b.copy()
Edit: There is no dictionary method that inserts the value by-value. Python dictionaries always use references.
精彩评论