[Tutor] how to delete some quasi-duplicated keys

Andreas Perstinger andreas.perstinger at gmx.net
Fri Nov 25 17:49:43 CET 2011


On 2011-11-25 13:40, lina wrote:
> On Fri, Nov 25, 2011 at 7:19 PM, Steven D'Aprano<steve at pearwood.info>  wrote:
>>  f = open("some file")
>>  dehydrons = {}
>>  occurrence = {}
>>  pairs = {}
>>  for line in f.readlines():
>>      parts = line.split()
>>      # convert to ints
>>      parts = [int(s) for s in parts]
>>      pair = frozenset(parts[:2])  # order doesn't matter
>>      if pair in dehydrons:
>>          occurrence[pair] += 1
>>      else:
>>          dehydrons[pair] = parts[2]
>>          occurrence[pair] = 1
>>          pairs[pair] = pairs.get(pair, 0) + parts[2]
>>  f.close()
>>
>          for line in f.readlines():
>              parts = line.split()
>              #pair=set((parts[0],parts[1]))
>              #convert to ints
>              parts = [int(s) for s in parts]
>              pair = frozenset(parts[:2])
>              print(pair)
>              if pair in dehydrons:
>                  occurence[pair] += 1
>              else:
>                  dehydrons[pair] = parts[2]
>                  pairs[pair] = pairs.get(pair,0) + parts[2]
>          print(pairs)
>
>
> $ python3 dehydron_data_frozenset_version.py
> frozenset({2, 15})
> frozenset({2, 15})
> Traceback (most recent call last):
>    File "dehydron_data_frozenset_version.py", line 35, in<module>
>      occurence[pair] += 1
> KeyError: frozenset({2, 15})

You want to add one to "occurence[frozenset({2, 15})]" but there is no 
such key in "occurence" yet.

If you carefully re-read Steven's code snippet you will see that you 
missed the line

occurence[pair] = 1

in the else-branch.

Therefore "occurence[frozenset({2, 15})]" wasn't set in the first 
iteration and you get the error in the second. You can see that you are 
already in the second iteration by looking at the output of your program 
before the error message.

Bye, Andreas


More information about the Tutor mailing list