1

i am a newbie in python and facing issue in getting this output

 a = [('textVerify', 'AH', 'SELECT SERVICES'), ('textVerify', 'F7', 'test1>'),('audioVerify', '091;0'), ('imageVerify', 'duck.gif'),('imageVerify', 'egg.gif')]

i want to create a new list which should hold all the 0th unique element like

  audioVerify,imageVerify,textVerify

so the result expected is

 ['textVerify',(('AH', 'SELECT SERVICES'), ('F7', 'test1>'))  'audioVerify', ('091;0'),  ('imageVerify', ('duck.gif','egg.gif')]
Ragav
  • 942
  • 4
  • 19
  • 37

4 Answers4

5

You'd better use a defaultdict for this:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for item in a:
...     d[item[0]].append(item[1:])
...
>>> d
defaultdict(<class 'list'>, {'textVerify': [('AH', 'SELECT SERVICES'), 
('F7', 'est1>')], 'imageVerify': [('duck.gif',), ('egg.gif',)], 
'audioVerify': [('091;0',)]})

Now you can access its elements by name/index:

>>> d['textVerify']
[('AH', 'SELECT SERVICES'), ('F7', 'test1>')]
>>> d['textVerify'][0][0]
'AH'

If you need to preserve the order of the dictionary keys, you can use an OrderedDict, together with the .setdefault() method, as described by Ashwini Chaudhary:

>>> d = OrderedDict()
>>> for x in a:
...     d.setdefault(x[0],[]).append(x[1:])
...
>>> d
OrderedDict([('textVerify', [('AH', 'SELECT SERVICES'), ('F7', 'test1>')]), 
('audioVerify', [('091;0',)]), ('imageVerify', [('duck.gif',), ('egg.gif',)])])
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
2

Using dict.setdefault(), this is slightly faster than defaultdict() at least for small lists.:

>>> a
[('textVerify', 'AH', 'SELECT SERVICES'), ('textVerify', 'F7', 'test1>'), ('audioVerify', '091;0'), ('imageVerify', 'duck.gif'), ('imageVerify', 'egg.gif')]
>>> d={}
>>> for x in a:
...     d.setdefault(x[0],[]).append(x[1:])
... 
>>> d
{'audioVerify': [('091;0',)], 'textVerify': [('AH', 'SELECT SERVICES'), ('F7', 'test1>')], 'imageVerify': [('duck.gif',), ('egg.gif',)]}

>>> d["audioVerify"]
[('091;0',)]
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> _ = [d[i[0]].append(i[1:]) for i in a]
>>> d['textVerify']
[('AH', 'SELECT SERVICES'), ('F7', 'test1>')]
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0
a = [('textVerify', 'AH', 'SELECT SERVICES'), ('textVerify', 'F7', 'test1>'),('audioVerify', '091;0'), ('imageVerify', 'duck.gif'),('imageVerify', 'egg.gif')]

c=set(i[0] for i in a)
d=dict()
for i in c:
        m=[]
        for v in a:
                if v[0]==i:
                        m.extend(list(v[1:]))
        if len(m) !=0:
                d[i]=m

print(d)
raton
  • 418
  • 5
  • 14