@@ -316,68 +316,25 @@ TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
316316>> >
317317```
318318
319- Dictionaries have an `update` method that adds everything from another
320- dictionary into it. So we can merge dictionaries like this:
319+ Usually it' s easiest to do this:
321320
322321```python
323- >> > merged = {}
324- >> > merged.update({' a' : 1 , ' b' : 2 })
325- >> > merged.update({' c' : 3 })
326- >> > merged
327- {' c' : 3 , ' b' : 2 , ' a' : 1 }
328- >> >
329- ```
330-
331- Or we can [write a function](../ basics/ defining- functions.md) like this:
332-
333- ```python
334- >> > def merge_dicts(dictlist):
335- ... result = {}
336- ... for dictionary in dictlist:
337- ... result.update(dictionary)
338- ... return result
339- ...
340- >> > merge_dicts([{' a' : 1 , ' b' : 2 }, {' c' : 3 }])
341- {' c' : 3 , ' b' : 2 , ' a' : 1 }
342- >> >
322+ >> > dict1 = {' a' : 1 , ' b' : 2 }
323+ >> > dict2 = {' c' : 3 }
324+ >> > {** dict1, ** dict2}
325+ {' a' : 1 , ' b' : 2 , ' c' : 3 }
343326```
344327
345- Kind of like counting things, merging dictionaries is also a commonly
346- needed thing and there ' s a class just for it in the `collections`
347- module. It ' s called ChainMap:
328+ Dictionaries also have an `update` method that adds everything from another
329+ dictionary into it, and you can use that too. This was the most common way to
330+ do it before Python supported `{ ** dict1, ** dict2}` .
348331
349332```python
350- >> > import collections
351- >> > merged = collections.ChainMap({' a' : 1 , ' b' : 2 }, {' c' : 3 })
333+ >> > merged = {}
334+ >> > merged.update({' a' : 1 , ' b' : 2 })
335+ >> > merged.update({' c' : 3 })
352336>> > merged
353- ChainMap({' b' : 2 , ' a' : 1 }, {' c' : 3 })
354- >> >
355- ```
356-
357- Our `merged` is kind of like the Counter object we created earlier. It' s
358- not a dictionary, but it behaves like a dictionary.
359-
360- ```python
361- >> > for key, value in merged.items():
362- ... print (key, value)
363- ...
364- c 3
365- b 2
366- a 1
367- >> > dict (merged)
368- {' c' : 3 , ' b' : 2 , ' a' : 1 }
369- >> >
370- ```
371-
372- Starting with Python 3.5 it' s possible to merge dictionaries like this.
373- ** Don' t do this unless you are sure that no-one will need to run your
374- code on Python versions older than 3.5 .**
375-
376- ```python
377- >> > first = {' a' : 1 , ' b' : 2 }
378- >> > second = {' c' : 3 , ' d' : 4 }
379- >> > {** first, ** second}
380- {' d' : 4 , ' c' : 3 , ' a' : 1 , ' b' : 2 }
337+ {' a' : 1 , ' b' : 2 , ' c' : 3 }
381338>> >
382339```
383340
0 commit comments