Duplicate keys in dict?

News123 news123 at free.fr
Sun Mar 7 11:46:02 EST 2010


vsoler wrote:
> Hello,
> 
> My code snippet reads data from excel ranges. First row and first
> column are column headers and row headers respectively. After reding
> the range I build a dict.
> 
> ................'A'..............'B'
> 'ab'............3................5
> 'cd'............7................2
> 'cd'............9................1
> 'ac'............7................2
> 
> d={('ab','A'): 3, ('ab','B'): 5, ('cd','A'): 7, ...
> 
> However, as you can see there are two rows that start with 'cd', and
> dicts, AFAIK do not accept duplicates.

Normall dicts are used if you want to access your data at a later point
in time by the key name.

Do you want to be able to do this?


Then what would you expect to receive for d[('cd','A')] ?

The first value? the second value? both values?

Could you perhaps change further occurences of 'cd' with 'cd1' , 'cd2' ,
'cd3',  ... ?

Not knowing your exact context makes it difficult to suggest solutions?

perhaps you could switch to a list containing a tuple of (rowname,rowdict)


l = [ ('ab', { 'A': 3 , 'B': 5 } ),
       'cd', { 'A': 7 , 'B': 2 } ),
       'cd', { 'A': 9 , 'B': 1 } ),
       'ac', { ... }
    ]


bye

N

> 
> What is the best workaround for this? Should I discard dicts? Should I
> somehow have under 'cd'... a list of values?
> 
> One of the difficulties I find here is that I want to be able to
> easily sum all the values for each row key:  'ab', 'cd' and 'ac'.
> However, using lists inside dicts makes it a difficult issue for me.
> 
> What is the best approach for this problem? Can anybody help?



More information about the Python-list mailing list