@@ -23,7 +23,7 @@ not. So we can do:
2323.. code :: python
2424
2525 from collections import defaultdict
26-
26+
2727 colours = (
2828 (' Yasoob' , ' Yellow' ),
2929 (' Ali' , ' Blue' ),
@@ -32,23 +32,23 @@ not. So we can do:
3232 (' Yasoob' , ' Red' ),
3333 (' Ahmed' , ' Silver' ),
3434 )
35-
35+
3636 favourite_colours = defaultdict(list )
37-
37+
3838 for name, colour in colours:
3939 favourite_colours[name].append(colour)
40-
40+
4141 print (favourite_colours)
42-
43- # output
44- # defaultdict(<type 'list'>,
45- # {'Arham': ['Green'],
46- # 'Yasoob': ['Yellow', 'Red'],
47- # 'Ahmed': ['Silver'],
42+
43+ # output
44+ # defaultdict(<type 'list'>,
45+ # {'Arham': ['Green'],
46+ # 'Yasoob': ['Yellow', 'Red'],
47+ # 'Ahmed': ['Silver'],
4848 # 'Ali': ['Blue', 'Black']
4949 # })
5050
51- One another very important use case is when you are appending to nested
51+ One other very important use case is when you are appending to nested
5252lists inside a dictionary. If a ``key `` is not already present in the
5353dictionary then you are greeted with a ``KeyError ``. ``defaultdict ``
5454allows us to circumvent this issue in a clever way. First let me share
@@ -73,7 +73,7 @@ share a solution using ``defaultdict``.
7373 some_dict[' colours' ][' favourite' ] = " yellow"
7474 # Works fine
7575
76- You can print the ``some_dict `` using ``json.dumps ``. Here is some
76+ You can print ``some_dict `` using ``json.dumps ``. Here is some
7777sample code:
7878
7979.. code :: python
@@ -92,7 +92,7 @@ colours:
9292.. code :: python
9393
9494 from collections import Counter
95-
95+
9696 colours = (
9797 (' Yasoob' , ' Yellow' ),
9898 (' Ali' , ' Blue' ),
@@ -101,13 +101,13 @@ colours:
101101 (' Yasoob' , ' Red' ),
102102 (' Ahmed' , ' Silver' ),
103103 )
104-
104+
105105 favs = Counter(name for name, colour in colours)
106106 print (favs)
107107 # Output: Counter({
108- # 'Yasoob': 2,
109- # 'Ali': 2,
110- # 'Arham': 1,
108+ # 'Yasoob': 2,
109+ # 'Ali': 2,
110+ # 'Arham': 1,
111111 # 'Ahmed': 1
112112 # })
113113
@@ -254,7 +254,7 @@ are immutable**. It means that this would not work:
254254 perry.age = 42
255255
256256 # Output: Traceback (most recent call last):
257- # File "", line 1, in
257+ # File "", line 1, in
258258 # AttributeError: can't set attribute
259259
260260 You should use named tuples to make your code self-documenting. **They
0 commit comments