[Tutor] obtaining values from a dictionary
Benoit Dupire
bdupire@seatech.fau.edu
Mon, 07 May 2001 00:39:34 -0400
This is my try...
I did not read all of the previous messages so i don't know very well the
context of your question...
I assume the question is well formulated.
This should do what you want:
for i in range(len(c)): # for each element of your list c
item1, item2 = c[i] # this element is a tuple --> break it
into 2 parts.
if d.has_key(item2): # if the 2nd part of the item is in the
dictionary d
c[i][1]= d[item2] # replace the 2nd part of the tuple
with the entry in the dict
if d.has_key(c[i]): # now there is a new tuple,
so we have to check whether it is or not, once again, in the dictionary
c[i] = d[c[i]] # if yes, we replace the
tuple with the entry in the dictionary.
A common pitfall for this algorithm is to do it like this:
for item1, item2 in c: # This does exactly like my first 2 lines.
It take an element of c, and breaks it into 2 parts.1
if d.has_key(item2): # if the 2nd part of the item is in
the d ictionary d
item2= d[item2] # replace the 2nd part of the tuple
------> Trap !!!! this line does not change the list, but the variable item2
See the difference..? i have to do something like c[index] to really change the
list.... IOW to refer to it explicitly.
Benoit
Julieta Rangel wrote:
> I have a list that looks like:
> c = [('a', ('a', 'a')), ('a', ('a', 'b')), ('a', ('b', 'a')), ('a', ('b',
> 'b')), ('b', ('a', 'a')), ('b', ('a', 'b')), ('b', ('b', 'a')), ('b', ('b',
> 'b'))]
>
> and I have a dictionary that looks like:
> d ={('b', 'a'): 'a', ('a', 'a'): 'a', ('a', 'b'): 'b', ('b', 'b'): 'b'}
>
> I want to replace the elements in my list according to my dictionary values.
> In other words, I want to go element by element on my list and ask the
> computer to give me the corresponding value, according to the dictionary.
> For example, if I want to get the value of my second element in my list
> ('a',('a','b')), according to my dictionary, this is equal to ('a','b'),
> which is equal to b. Can this be done?
>
> Julieta
>
> _________________________________________________________________
> Get your FREE download of MSN Explorer at http://explorer.msn.com
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Benoit Dupire
Graduate Student
----------------
I'd like to buy a new Boomerang. How can i get rid of the old one?