dictionary help

J. Cliff Dyer jcd at sdf.lonestar.org
Mon Aug 10 23:07:49 EDT 2009


On Mon, 2009-08-10 at 22:11 -0400, Krishna Pacifici wrote:
> Hi,
> kind of a newbie here, but I have two questions that are probably
> pretty simple.
> 
> 1.  I need to get rid of duplicate values that are associated with
> different keys in a dictionary.  For example I have the following
> code.
> s={}
> s[0]=[10,2,3]
> s[10]=[22,23,24]
> s[20]=[45,5]
> s[30]=[2,4]
> s[40]=[6,7,8]
> 
> Now I want to be able to loop through the primary keys and get rid of
> duplicates (both in keys and values) so that I would have either a new
> dictionary or the same dictionary but with the following values:
> 
> s[0]=[3]
> s[10]=[22,23,24]
> s[20]=[45,5]
> s[30]=[2,4]
> s[40]=[6,7,8]
> 
> It doesn't matter which value gets removed as long as there is only
> one remaining, so in this example it doesn't matter that 2 got removed
> from s[0] or from s[30] as long as there is only one 2 in the
> dictionary.
> 
So if the number is a key, you want to keep the key, and delete all
matching values, and if the number is not a key, you want to keep one
(any one) instance of that number?  I'm not sure that what you are
looking for is best represented by a dict.  You might want to consider
creating your own class and overriding __getitem__.


> 2.  I need to be able to loop over the values in the dictionary when
> there are multiple values assigned to each key like above and assign
> new values to those values.  Taking the above example I would want to
> assign a new value so that when you called s[0] it would equal [3,4]
> say if 4 was the new value.  I think this should be as simple as
> adding a value, but I kept on having difficulty.
> 
Here you might want to either use the append() method on the lists of
each entry.

> Any suggestions would be greatly appreciated.
> 
I'm not sure what you are doing maps cleanly to currently existing
datastructures, which means that there might not be a quick shortcut for
you.  Hammer out the specs of what you want your class to be able to do,
and what the API will be for performing each of those functions.  Then
you should be able to begin implementing it, or at least come up with
some more specific questions.



> Thank you very much,
> Krishna

Cheers,
Cliff





More information about the Python-list mailing list