Home > Software design >  List in List to dictionary
List in List to dictionary

Time:08-28

I have a route list and want to transform it to a dictionary...

routes=[[0, 1, 9, 3, 0], [0, 2, 4, 7, 0], [0, 6, 0], [0, 8, 11, 5, 0], [0, 10, 0]]

I tried different methods but had no success. It's definitely super easy but I have no idea.

I'm trying to get a dict like this:

dict= {0: [0, 1, 3, 9, 0], 1: [0, 2, 4, 7, 0], 2: [0, 6, 0], 3: [0, 8, 11, 5, 0], 4:[0, 10, 0]}

CodePudding user response:

I don't know why you need that, but here is how you can achieve with dict and enumerate builtins:

>>> dict(enumerate(routes))
# output:
{0: [0, 1, 9, 3, 0], 1: [0, 2, 4, 7, 0], 2: [0, 6, 0], 3: [0, 8, 11, 5, 0], 4: [0, 10, 0]}

CodePudding user response:

routes=[[0, 1, 9, 3, 0], [0, 2, 4, 7, 0], [0, 6, 0], [0, 8, 11, 5, 0], [0, 10, 0]]
dict={i: routes[i] for i in range(len(routes))}
print(dict)

#Output
{0: [0, 1, 9, 3, 0], 1: [0, 2, 4, 7, 0], 2: [0, 6, 0], 3: [0, 8, 11, 5, 0], 4: [0, 10, 0]}

For more understanding please visit Click here website.

  • Related