Namedtuples problem

MRAB python at mrabarnett.plus.com
Thu Feb 23 18:58:35 EST 2017


On 2017-02-23 22:51, Deborah Swanson wrote:
> Peter Otten wrote, on February 23, 2017 2:34 AM
[snip]
>> #untested
>>
>> def split_into_groups(records, key):
>>     groups = defaultdict(list)
>>     for record in records:
>>         # no need to check if a group already exists
>>         # an empty list will automatically added for every
>>         # missing key
>>         groups[key(record)].append(record)
>>     return groups
>
> I used this approach the first time I tried this for both defaultdict
> and OrderedDict, and for both of them I immediately got a KeyError for
> the first record. groups is empty, so the title for the first record
> wouldn't already be in groups.
>
If the key isn't already in the dictionary, a defaultdict will create 
the entry whereas a normal dict will raise KeyError.

> Just to check, I commented out the extra lines that I added to handle
> new keys in my code and immediately got the same KeyError.
>
> My guess is that while standard dictionaries will automatically make a
> new key if it isn't found in the dict, defaultdict and OrderedDict will
> not. So it seems you need to handle new keys yourself. Unless you think
> I'm doing something wrong and dicts from collections should also
> automatically make new keys.
>
defaultdict will, dict and OrderedDict won't.

[snip]




More information about the Python-list mailing list