Reputation: 524
For example, convert
d = {'a.b1': [1,2,3], 'a.b2': [3,2,1], 'b.a1': [2,2,2]}
to
l = [['a','b1',1,2,3], ['a','b2',3,2,1], ['b','a1',2,2,2]]
What I do now
l = []
for k,v in d.iteritems():
a = k.split('.')
a.extend(v)
l.append(a)
is definitely not a pythonic way.
Upvotes: 4
Views: 84
Reputation: 5942
Python 2:
d = {'a.b1': [1,2,3], 'a.b2': [3,2,1], 'b.a1': [2,2,2]}
l = [k.split('.') + v for k, v in d.iteritems()]
Python 3:
d = {'a.b1': [1,2,3], 'a.b2': [3,2,1], 'b.a1': [2,2,2]}
l = [k.split('.') + v for k, v in d.items()]
These are called list comprehensions.
Upvotes: 8
Reputation: 17132
You can do this:
>>> d = {'a.b1': [1,2,3], 'a.b2': [3,2,1], 'b.a1': [2,2,2]}
>>> print([k.split(".") + v for k, v in d.items()])
[['b', 'a1', 2, 2, 2], ['a', 'b1', 1, 2, 3], ['a', 'b2', 3, 2, 1]]
Upvotes: 5