[Tutor] how to delete some quasi-duplicated keys

Alan Gauld alan.gauld at btinternet.com
Fri Nov 25 13:06:35 CET 2011


On 25/11/11 08:41, lina wrote:
>>>> pairs
> {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25}
>
>
> such as here ('66', '69') and ('69', '66') is one key,
>
> I wanna keep only one and add the value of those two keys, above is a
> very simple example:
>
> here is the (failed) code:
>
>          for k, v in pairs.items():
>              if str(k)[1]+str(k)[0] in pairs.keys():

I don;t think this does what you think it does.

k is a key from pairs which looks like ('66', '69')
You convert that to a string (with str(k)) which
yields : "('66', '69')"

You then add the first two characters of that string.
Those are ( and ' so you get a value of (' and ask whether that appeats 
in pairs.keys() which it will not because the keys are tuples.

So the if block never happens

>                  print(pairs[str(k)[1]+str(k)[0]])
>                  pairs[k]+=pairs[str(k)[1]+str(k)[0]]
>                  del pairs[str(k)[1]+str(k)[0]]


>              print(v,k)

And you print the original value followed by the tuple key.

I'm pretty sure thats not what you want.

Maybe you are trying to add the two elements of the tuple?
But even that won't disambiguate between (66,69) and (69,66)
You would need to sort the tuples first so that both would
render 66,69.

HTH,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list