Hi,

I have a dictionary with the key as a tuple.

 x = { ('AA',1,3):0.56, ('BB',0,3):0.70, ('AA',1,3):0.10, ('CC',1,3):0.60  }

I would like to get all the values where the key is equal to...

('AA',1,3)

However, when I use it only returns the last value where ('AA',1,3) is found.

 x.get( ('AA',1,3) )

How would I do this to get all the values where ('AA,1,3) is satisfied. Therefore, I would like something where I can return both 0.56 and 0.10.

Recommended Answers

All 8 Replies

You must collect values as list or other collection type. Now you overwrite values and only last stays.

You could create your own class based on dictionary that checks whether that key already exists in __setattr__ and then add the value to a list/tuple. When you do your get() you can then use isinstance to act accordingly.

You can also use defaultdict(list) (form module collections) and append values there.

Ok, I'm a little unsure how to implement this. Is their any example or link that you think would help clarify for this for me? Thanks.

from collections import defaultdict
values = defaultdict(list)
for n in range(20):
    values[n % 2].append(n)
print values
"""Output:
defaultdict(<type 'list'>, {0: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18], 1: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]})
"""

Thanks PyTony. That is actually really helpful.

Is there any way to slice the dictionary to look for values. Here is sample code that I created.

from collections import defaultdict

x = [ ('SET',1,2,1,1,0.23333),('SET',1,2,1,1,0.333),('SET',2,2,1,1,0.5),('SET',2,2,1,1,0.1), ('SET',1,2,1,1,0.333), ('RESET',2,2,1,1,0.272) ]
d = defaultdict(list)
for aa,bb,cc,dd,ee,ff in x:
    d[aa,bb,cc,dd,ee].append(ff)
d.get(('SET',1,2,1,1))

The number that I am interested in is the last number of my key tuple.
With my current d.get(('SET',1,2,1,1)) I would get a list [0.23333,0.3333]. Is there any way to slice this dictionary so that I could just specify

   d.get( ('SET') ) 

and return the other values in the key that correspond to all key tuples that have 'SET' instead of having to do d.get(('SET',1,2,1,1))

Something like:

from collections import defaultdict

d = defaultdict(list)
for key, value in ( (('SET',1,2,1,1),0.23333),
                    (('SET',1,2,1,1),0.333),
                    (('SET',2,2,1,1),0.5),
                    (('SET',2,2,1,1),0.1),
                    (('SET',1,2,1,1),0.333),
                    (('RESET',2,2,1,1),0.272)
                    ):
    d[key].append(value)

print d
print [d[key] for key in d if key[0]=='SET']
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.