[Tutor] handling tuples in a dictionary

Don Arnold darnold02 at sprynet.com
Sun Sep 28 12:14:35 EDT 2003


----- Original Message -----
From: "Jimmy verma" <jim_938 at hotmail.com>
To: <tutor at python.org>
Sent: Sunday, September 28, 2003 9:31 AM
Subject: [Tutor] handling tuples in a dictionary


> Hello,
>
> Thanks to everyone on tutor list for providing their valuable support.
>
> I am having my problem like this:
>
> I have a dictionary with items of the following form:
>
> dict = {('x',1): -100, ('y',2):-200, ('x',2):100, ('z',3):150, ('y',
4):50}
>
> I have tuple as the keys.
>
>
> What i want is to have this information in this form in order to make the
> combinations:
>
> Letter  'X'
> set     1   R  -100
> set    2   R  100
>
>
> Letter 'Y'
> set  2  R  -200
> set  4  R  50
>
>
> Letter 'Z'
> set  3  R  150
>
>
>
> I mean i want for all the tuples that whose first letter is same they
should
> be put in one group and their values listed like i have written above.
>
>
> I have tried to take the dict.keys() and then sort these values but not
> getting to know completely how can i achieve this.
>
> You suggestions will be highly appriciated.
>
> Thanks in advance.
>
> Regards,
>
> J+

I'm sure this isn't the most succinct way to do it, but it's fairly easy to
follow:

mydict = {('x',1): -100, ('y',2):-200, ('x',2):100, ('z',3):150, ('y',
4):50}
newdict = {}

for akey in mydict.keys():
    if newdict.has_key(akey[0]):
        newdict[akey[0]].append((akey[1],mydict[akey]))
    else:
        newdict[akey[0]] = [(akey[1],mydict[akey])]

keylist = newdict.keys()
keylist.sort()

for akey in keylist:
    print 'letter', akey
    for atuple in newdict[akey]:
        print 'set', atuple[0], 'R', atuple[1]

>>>
>>>letter x
>>>set 1 R -100
>>>set 2 R 100
>>>letter y
>>>set 2 R -200
>>>set 4 R 50
>>>letter z
>>>set 3 R 150
>>>

HTH,
Don




More information about the Tutor mailing list