deman
deman

Reputation: 41

Convert list to dictionary of tuples based on column value

I'm trying to convert the following lists in Python:

headers = [ 'Col1','Col2','Col3','Col4' ]
data    = [[  '1','A','D','X']
           [  '2','A','D','X']  
           [  '3','A','C','X']  
           [  '1','B','F','X']
           [  '2','B','F','X'] ]

to a dictionary of tuples with the Col2 used as the unique key so the output would like like below:

{ 
  'A': [( '1','D','X'),('2','D','X'),('3','C','X') ]
  'B': [( '1','F','X'),('2','F','X') ]
}

So far I've managed to transpose and zip it to a dictionary with columns as keys but I stucked there.

transpose_result = map(list, zip(*data))
data = dict(zip(headers, transpose_result))

Can you help? Thanks in advance.

Upvotes: 3

Views: 148

Answers (2)

SuperNova
SuperNova

Reputation: 27476

Hope this helps..

data    = [[  '1','A','D','X'],
           [  '2','A','D','X'],
           [  '3','A','C','X'],
           [  '1','B','F','X'],
           [  '2','B','F','X'] ]

res = {}

for d in data:
   key = d[1]
   d.remove(key)
   if key in res.keys():
          res[key].append(d)
   else:
          res[key] = [d]

Upvotes: 0

falsetru
falsetru

Reputation: 369274

Iterate the data list items, and build new dictionary with row[1] as a key and row[:1] + row[2:] for values (list items):

>>> data = [
...     ['1','A','D','X'],
...     ['2','A','D','X'],
...     ['3','A','C','X'],
...     ['1','B','F','X'],
...     ['2','B','F','X'],
... ]

>>> d = {}
>>> for row in data:
...     d.setdefault(row[1], []).append(row[:1] + row[2:])
... 
>>> d
{'B': [['1', 'F', 'X'], ['2', 'F', 'X']],
 'A': [['1', 'D', 'X'], ['2', 'D', 'X'], ['3', 'C', 'X']]}

dict.setdefault is used to populate the dictionary with a empty list when there's no key in the dictionary, so the list.append call can be done safely.


If you use collections.defaultdict, it could be simpler:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for row in data:
...     d[row[1]].append(row[:1] + row[2:])
... 
>>> d
defaultdict(<type 'list'>, {
    'A': [['1', 'D', 'X'], ['2', 'D', 'X'], ['3', 'C', 'X']],
    'B': [['1', 'F', 'X'], ['2', 'F', 'X']]})
>>> dict(d)  # to convert it back to dict
{'A': [['1', 'D', 'X'], ['2', 'D', 'X'], ['3', 'C', 'X']],
 'B': [['1', 'F', 'X'], ['2', 'F', 'X']]}

Upvotes: 6

Related Questions