| 144 | === Similar version with a dict, counts any hashable types === |
| 145 | |
| 146 | The previous function can only count occurrences of numbers. |
| 147 | This counts occurrences of any hashable types and returns a dict instead of a list. |
| 148 | {{{ |
| 149 | #!python |
| 150 | def countitemoccurrences(items, requireditems=[]): |
| 151 | """Takes a list of hashable items and returns a dict whose keys are those |
| 152 | items and the values are the counts of how many times each item appers in the list. |
| 153 | |
| 154 | If the list requireditems is specified it's values are guaranteed to be keys |
| 155 | in the resulting dict, even if they don't appear in items in which case the count will be 0 |
| 156 | |
| 157 | Examples: |
| 158 | >>> counttypes('blue green green'.split(), 'blue red green'.split()) |
| 159 | {'blue': 1, 'green': 2, 'red': 0} |
| 160 | """ |
| 161 | counts = dict() |
| 162 | for i in requireditems: |
| 163 | counts[i] = 0 |
| 164 | for i in items: |
| 165 | counts[i] = counts.get(i, 0) + 1 |
| 166 | return counts |
| 167 | }}} |
| 168 | |