Convert tuple to list in a dictionary

青春壹個敷衍的年華 提交于 2019-12-24 07:05:12

问题


I have a dictionary like this:

a= {1982: [(1,2,3,4)],
    1542: [(4,5,6,7),
           (4,6,5,7)]}

and I want to change the all the tuples (1,2,3,4),(4,5,6,7),(4,6,5,7) to lists, in this case: [1,2,3,4], [4,5,6,7], [4,6,5,7]

I have tried

for key, value in a.items():
    for i in value:
        i = tuple(i)

but it does now work. How can I achieve it?


回答1:


As far as I understand you want to convert each tuple in a list. You can do this using a dictionary comprehension:

{k: [list(ti) for ti in v] for k, v in a.items()}

will give

{1542: [[4, 5, 6, 7], [4, 6, 5, 7]], 1982: [[1, 2, 3, 4]]}

Is that what you are after?




回答2:


In-place:

for key, value in a.items():
    for i, t in enumerate(value):
        value[i]= list(t)

New objects:

{key: [list(t) for t in value] for key, value in a.items()}



回答3:


You can use "tupleo" library

from tupleo import tupleo.

val = tupleo.tupleToList(a[1542]).

print(val) [[4,5,6,7], [4,6,5,7]]

tupleo gives you full depth level conversion of tuple to list. and it have functionality to convert tuple to dict also based on index.



来源:https://stackoverflow.com/questions/47731301/convert-tuple-to-list-in-a-dictionary

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