Lee
Lee

Reputation: 524

What is the pythonic way to this dict to list conversion?

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

Answers (2)

ChrisP
ChrisP

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

Mohammed Aouf Zouag
Mohammed Aouf Zouag

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

Related Questions