|
143 | 143 | res += data[d] |
144 | 144 | print(res) |
145 | 145 | # 6 |
| 146 | + |
| 147 | + |
| 148 | +### copy between dictionaries |
| 149 | + |
| 150 | +# SHALLOW copy |
| 151 | + |
| 152 | +import copy |
| 153 | + |
| 154 | +a_dict = { |
| 155 | + 'first name': 'James', |
| 156 | + 'last name': 'Bond', |
| 157 | + 'movies': ['Goldfinger (1964)', 'You Only Live Twice'] |
| 158 | + } |
| 159 | +b_dict = (a_dict) |
| 160 | +print('Memory chunks:', id(a_dict), id(b_dict)) |
| 161 | +# Memory chunks: 2452251144960 2452251144960 |
| 162 | + |
| 163 | +print('Same memory chunk?', a_dict is b_dict) |
| 164 | +# Same memory chunk? True |
| 165 | + |
| 166 | +a_dict['movies'].append('Diamonds Are Forever (1971)') |
| 167 | +print('a_dict movies:', a_dict['movies']) |
| 168 | +# a_dict movies: ['Goldfinger (1964)', 'You Only Live Twice', 'Diamonds Are Forever (1971)'] |
| 169 | +print('b_dict movies:', b_dict['movies']) |
| 170 | +# b_dict movies: ['Goldfinger (1964)', 'You Only Live Twice', 'Diamonds Are Forever (1971)'] |
| 171 | + |
| 172 | +# DEEP copy |
| 173 | + |
| 174 | +import copy |
| 175 | + |
| 176 | +a_dict = { |
| 177 | + 'first name': 'James', |
| 178 | + 'last name': 'Bond', |
| 179 | + 'movies': ['Goldfinger (1964)', 'You Only Live Twice'] |
| 180 | + } |
| 181 | +b_dict = copy.deepcopy(a_dict) |
| 182 | +print('Memory chunks:', id(a_dict), id(b_dict)) |
| 183 | +# Memory chunks: 2349147026176 2349144587520 |
| 184 | + |
| 185 | +print('Same memory chunk?', a_dict is b_dict) |
| 186 | +# Same memory chunk? False |
| 187 | + |
| 188 | +a_dict['movies'].append('Diamonds Are Forever (1971)') |
| 189 | +print('a_dict movies:', a_dict['movies']) |
| 190 | +# a_dict movies: ['Goldfinger (1964)', 'You Only Live Twice', 'Diamonds Are Forever (1971)'] |
| 191 | +print('b_dict movies:', b_dict['movies']) |
| 192 | +# b_dict movies: ['Goldfinger (1964)', 'You Only Live Twice'] |
| 193 | + |
0 commit comments