Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tuple to dict:one key and multiple values

How to convert the tuple:

t=(('1','a'), ('1','A'), ('2','b'), ('2','B'), ('3','c'),('3', 'C'))

into a dictionary:

{'1':('a','A'),'2':('b','B'),'3':('c','C')}

I have tried in a console:

>>> d={}
>>> t[0]
(1, 'a')
>>> d[t[0][0]]=t[0][1]
>>> d
{1: 'a'}
>>> t[0][0] in d
True
>>> d[t[1][0]]=t[1][1]
>>> d
{1: 'A'}
>>> d[t[0][0]]=t[0][1]
>>> d[t[1][0]]=d[t[1][0]],t[1][1]
>>> d
{1: ('a', 'A')}

Now the following script fails doing the job:

t=(('1','a'), ('1','A'), ('2','b'), ('2','B'), ('3','c'),('3', 'C'))
print "{'1':('a','A'),'2':('b','B'),'3':('c','C')} wanted, not:",dict(t)
d={}

for c, ob in enumerate(t):
   print c,ob[0], ob[1]
   if ob[0] in d:
       print 'test'
       d[ob[0]]=d[ob[0]],ob[1]
       print d

   else:
       print 'else', d, ob[0],ob[1]
       d[ob[0]]=d[ob[1]]           # Errror is here
       print d
print d

I have the error:

Traceback (most recent call last):
  File "/home/simon/ProjetPython/python general/tuple_vers_dic_pbkey.py", line 20, in <module>
    d[ob[0]]=d[ob[1]]
KeyError: 'a'

It seems to be different from $>>> d[t[0][0]]=t[0][1]$ . Thanks for your help

JP

PS Is there a better way to do the convertion?

like image 877
Jean-Pat Avatar asked Sep 27 '12 11:09

Jean-Pat


2 Answers

You can use defaultdict from the collections module (although it will work better for lists, not tuples):

t=(('1','a'), ('1','A'), ('2','b'), ('2','B'), ('3','c'),('3', 'C'))

from collections import defaultdict
d = defaultdict(list)
for k, v in t:
    d[k].append(v)

d = {k:tuple(v) for k, v in d.items()}
print d

or simply add tuples together:

t = (('1','a'), ('1','A'), ('2','b'), ('2','B'), ('3','c'),('3', 'C'))
d = {}
for k, v in t:
    d[k] = d.get(k, ()) + (v,)
print d    
like image 120
georg Avatar answered Sep 24 '22 19:09

georg


import itertools as it
t=(('1','a'), ('1','A'), ('2','b'), ('2','B'), ('3','c'),('3', 'C'))

{k:tuple(x[1] for x in v) for k,v in it.groupby(sorted(t), key=lambda x: x[0])}

returns

{'1': ('A', 'a'), '2': ('B', 'b'), '3': ('C', 'c')}
like image 30
eumiro Avatar answered Sep 24 '22 19:09

eumiro