Dictionary newFrom: and duplicated keys

MD
Marcus Denker
Tue, May 10, 2022 6:23 AM

Hi,

Dictionary class>>#newFrom: right now raises an error if it sees duplicated keys.

newFrom: aDictionaryOrCollectionOfAssociations
"Answer an instance of me containing the same associations as the argument.
Error if any key appears twice."

| newDictionary |
newDictionary := self new: aDictionaryOrCollectionOfAssociations size.
aDictionaryOrCollectionOfAssociations associationsDo:
	[:x |
	(newDictionary includesKey: x key)
		ifTrue: [self error: 'Duplicate key: ', x key printString]
		ifFalse: [newDictionary add: x]].
^ newDictionary

this leads to  an error for:

{#a->1. #a->2} asDictionary

While just creating it with new and putting the data of course has no problem
with duplicated keys:

Dictionary new
at: #a put: 1;
at: #a put: 2;
yourself

We have a suggestion to remove the error.

PR is here:

https://github.com/pharo-project/pharo/pull/11176 <https://github.com/pharo-project/pharo/pull/11176>

(as a side-effect, this speed up asDictionary a little, too)

Marcus
Hi, Dictionary class>>#newFrom: right now raises an error if it sees duplicated keys. newFrom: aDictionaryOrCollectionOfAssociations "Answer an instance of me containing the same associations as the argument. Error if any key appears twice." | newDictionary | newDictionary := self new: aDictionaryOrCollectionOfAssociations size. aDictionaryOrCollectionOfAssociations associationsDo: [:x | (newDictionary includesKey: x key) ifTrue: [self error: 'Duplicate key: ', x key printString] ifFalse: [newDictionary add: x]]. ^ newDictionary this leads to an error for: {#a->1. #a->2} asDictionary While just creating it with new and putting the data of course has no problem with duplicated keys: Dictionary new at: #a put: 1; at: #a put: 2; yourself We have a suggestion to remove the error. PR is here: https://github.com/pharo-project/pharo/pull/11176 <https://github.com/pharo-project/pharo/pull/11176> (as a side-effect, this speed up asDictionary a little, too) Marcus