Question

Do you know a better/faster solution to convert this list

['foo1:bar1', 'foo2:bar2', 'foo3:bar3']

into the following dictionary

{'col2': ['bar1', 'bar2', 'bar3'], 'col1': ['foo1', 'foo2', 'foo3']}

The current version seems a little weird and possibly slow because of the two for loops.

tuples = ['foo1:bar1', 'foo2:bar2', 'foo3:bar3']
tuples_separated = [one.split(':') for one in tuples]
tidied = {'col1': [], 'col2': []}
for one in tuples_separated:
    tidied['col1'].append(one[0])
    tidied['col2'].append(one[1])
Was it helpful?

Solution

Use zip to zip the items?

In [15]: d={}
    ...: vals=zip(*(i.split(':') for i in tuples))
    ...: d['col1'], d['col2']=vals
    ...: print d
{'col2': ('bar1', 'bar2', 'bar3'), 'col1': ('foo1', 'foo2', 'foo3')}

OTHER TIPS

You could use:

dict(zip(('col1', 'col2'), 
     zip(*[item.split(':') for item in x])))

In [93]: x = ['foo1:bar1', 'foo2:bar2', 'foo3:bar3']

In [94]: [item.split(':') for item in x]
Out[94]: [['foo1', 'bar1'], ['foo2', 'bar2'], ['foo3', 'bar3']]

In [95]: zip(*[item.split(':') for item in x])
Out[95]: [('foo1', 'foo2', 'foo3'), ('bar1', 'bar2', 'bar3')]

In [96]: dict(zip(('col1', 'col2'), zip(*[item.split(':') for item in x])))
Out[96]: {'col1': ('foo1', 'foo2', 'foo3'), 'col2': ('bar1', 'bar2', 'bar3')}

You can also try this, which works for an arbitrary number of columns:

>>> tuples = ['foo1:bar1', 'foo2:bar2', 'foo3:bar3']
>>>
>>> {'col'+str(i+1):t for i,t in enumerate(zip(*(s.split(':') for s in tuples)))}
{'col2': ('bar1', 'bar2', 'bar3'), 'col1': ('foo1', 'foo2', 'foo3')}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top