dict.updateが使えますが、単純に使うとin-placeで処理されて元の辞書が変更されるので、必要に応じてcopyすると良いと思います。
python
1dict_A = {"a": 0, "b": 0, "c": 0,"d": 0,"e": 0,"f": 0}
2dict_B = {"c": 10, "f": 15}
3
4new_dict_A = dict_A.copy()
5new_dict_A.update(dict_B)
6print(dict_A)
7print(new_dict_A)
8""" =>
9{'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0}
10{'a': 0, 'b': 0, 'c': 10, 'd': 0, 'e': 0, 'f': 15}
11"""
で、要素数にもよりますが、ループで書いてもそんなに遅くはないかと。
python
1import timeit
2
3dict_A = {"a": 0, "b": 0, "c": 0,"d": 0,"e": 0,"f": 0}
4dict_B = {"c": 10, "f": 15}
5
6def f1():
7 new_dict_A = dict_A.copy()
8 for k, v in dict_B.items():
9 new_dict_A[k] = v
10 return new_dict_A
11
12def f2():
13 new_dict_A = dict_A.copy()
14 new_dict_A.update(dict_B)
15 return new_dict_A
16
17print(timeit.timeit(f1)) # => 0.5886494450096507
18print(timeit.timeit(f2)) # => 0.46052658899861854
19
元々ない要素は更新しないとか、柔軟なことをやりたければループの方が向いているかもしれません。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/07/14 22:38
2019/07/14 22:59 編集
2019/07/14 22:59