Convert dict of nested lists to list of tuples

 ̄綄美尐妖づ 提交于 2020-01-01 08:34:46

问题


I have dict of nested lists:

d = {'a': [[('a1', 1, 1), ('a2', 1, 2)]], 'b': [[('b1', 2, 1), ('b2', 2, 2)]]}
print (d)
{'b': [[('b1', 2, 1), ('b2', 2, 2)]], 'a': [[('a1', 1, 1), ('a2', 1, 2)]]}

I need create list of tuples like:

[('b', 'b1', 2, 1), ('b', 'b2', 2, 2), ('a', 'a1', 1, 1), ('a', 'a2', 1, 2)]

I tried:

a = [[(k, *y) for y in v[0]] for k,v in d.items()]
a = [item for sublist in a for item in sublist]

I think my solution is a bit over-complicated. Is there some better, more pythonic, maybe one line solution?


回答1:


You were almost there:

[(k, *t) for k, v in d.items() for t in v[0]]

The v[0] is needed because your values are just single-element lists with another list contained. The above can be expanded to the following nested for loops, if you wanted to figure out what it does:

for key, value in d.items():   # value is [[(...), (...), ...]]
    for tup in value[0]:  # each (...) from value[0]
        (key, *tup)  # produce a new tuple

Demo:

>>> d = {'a': [[('a1', 1, 1), ('a2', 1, 2)]], 'b': [[('b1', 2, 1), ('b2', 2, 2)]]}
>>> [(k, *t) for k, v in d.items() for t in v[0]]
[('a', 'a1', 1, 1), ('a', 'a2', 1, 2), ('b', 'b1', 2, 1), ('b', 'b2', 2, 2)]


来源:https://stackoverflow.com/questions/45233422/convert-dict-of-nested-lists-to-list-of-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!