简体   繁体   中英

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.

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 .

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM