0

In python, I have a dictionary named dict_a :

dict_a = {'a':1}

and I want to get a new dictionary dict_b as the update of dict_a,at the same time I don't want to change the dict_a, so I used this:

dict_b = copy.deepcopy(dict_a).update({'b':2})

However, the return value of dict.update is None, so the above code doesn't work. And I have to use this:

temp = copy.deepcopy(dict_a)
temp.update({'b':2})
dict_b = temp

The question is, how to get my goal in one line? Or some

spring cc
  • 937
  • 1
  • 10
  • 19

1 Answers1

0

What about:

>>> a = {'a':1}
>>> update = {'b': 1}
>>> b = dict(a.items() + update.items())
>>> b
{'a': 1, 'b': 1}

update - is your value that need to update(extend) dict a

b - is a new resulting dict

Anfd in this case a stay unchanged

wolendranh
  • 4,202
  • 1
  • 28
  • 37
  • I still wondering how to get the results of `copy.deepcopy(dict_a).update({'b':2})`, the results seems disappeared somehow. – spring cc Nov 18 '16 at 12:50
  • @springcc you can also do `a = {'a':1}; b = {'b':2}; {k: v for d in [a, b] for k, v in d.items()}` – wolendranh Nov 18 '16 at 12:56