On Sat, Nov 26, 2011 at 12:49 AM, Andreas Perstinger <andreas.perstin...@gmx.net> wrote: > On 2011-11-25 13:40, lina wrote: >> >> On Fri, Nov 25, 2011 at 7:19 PM, Steven D'Aprano<st...@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. Thanks, I was so careless.
for k, v in occurence.items(): print(v,k) 292 frozenset({66, 69}) 222 frozenset({24, 27}) How can I let the result like: 292 {66,69} 222 {24,27} don't output the frozenset > > 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 > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor