Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 562
Lee Avatar asked Dec 11 '22 18:12

Lee


1 Answers

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.

like image 127
ChrisP Avatar answered Dec 27 '22 04:12

ChrisP