Like almost always, the easiest way to understand this is to print
Now,
When we do
data
.data
is tuple of tuples. Each of these inner tuples is one row. Each element in one such tuple is the value in a single cell. Tuple
is an iterable
, i.e. you can iterate over its elements one by one. That is why you can do for row in data:
. In each iteration of the loop row will hold next sub-tuple.Now,
defaultdict(list)
has effect on groups[group].append(row)
. Here is the docs for defaultdict. In this case, using list, it will have default value of empty list. When we do
groups[group].append(row)
we append respective row to the value for key group
(Note that group
is variable, it will have some values like '1', '2', '3' or '4', depending what is the last char in the last element (row[-1][-1]
) in the respective row (tuple). What will happen if we were not using defaultdict
but ordinary dict and there was no such key in the dict? Yes, you will get KeyError. With the defaultdict
in our case it just creates empty list, map it to key group
and allow you to append row to that list, without raising an exception. Of course there is way to do something like this also with normal dict, but with defaultdict is more convenient.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs