1

If you had a list of lists like mylist below

mylist = [['start', 'a', 'next'],['next','b','end'],['previous','c','start']]

how would you create a dictionary where the key is equal to list[0][0] and the value=list

for example the dictionary would be:

{'start': ('a', 'next'), 'next': ('b', 'end'), 'previous': ('c', 'start')}

I am trying to create a transition function to traverse through a lists of lists which hold the transitions.

NEW

I am now trying to do a list comprehension but I keep getting "IndexError: string index out of range" with this code

d = {x[0]: (x[1],x[2]) for x in self.epsilon}
print(d)

my list is stored in self.epsilon which equals: self.epsilon = [['q1', '0', 'q1'],['q1','1', 'q2'], ['q2','0','q2'], ['q2', '1', 'q1']]

  • I have copy-pasted your snippet & I cannot reproduce the mentioned error. Are you sure you are getting the error due to dict comprehension? If yes, are you sure the contents of `self.epsilon` is the same as the one you have mentioned? I suspect `self.epsilon` could be a flat list of strings & not the nested structure. – Sriram Dec 04 '14 at 06:56

4 Answers4

2

The easiest way would be to do a dictionary comprehension:

{x[0]: tuple(x[1:]) for x in mylist}

This requires that each element in mylist is an array with at least an element in index 0 to be used as a key, and creates a tuple from the remaining elements in each nested array to be used as the value for the associated key.

Hart Simha
  • 862
  • 8
  • 14
0
mylist = [['start', 'a', 'next'],['next','b','end'],['previous','c','start']]
dic={}
for i in mylist:
    dic[i[0]]=i[1:]
print dic

If you dont want list but tuple as value of dict use

mylist = [['start', 'a', 'next'],['next','b','end'],['previous','c','start']]
dic={}
for i in mylist:
    dic[i[0]]=tuple(i[1:])
print dic
vks
  • 67,027
  • 10
  • 91
  • 124
  • Dictionary comprehensions solve this in a way more legible way. At the very least, `dict((key, value) for …)` does this too, for older versions of Python. – Eric O. Lebigot Dec 04 '14 at 06:28
0

In python 3 and 2.7:

a_list = [['start', 'a', 'next'],['next','b','end'],['previous','c','start']]


a_dict = {l[0]: (l[1], l[2]) for l in a_list}

print(a_dict)
# {'start': ('a', 'next'), 'previous': ('c', 'start'), 'next': ('b', 'end')}

Alterantive way:

a_dict = dict([[lst[0], (l[1], l[2])] for l in a_list]) 
# {'start': ('a', 'next'), 'previous': ('c', 'start'), 'next': ('b', 'end')}
Marcin
  • 215,873
  • 14
  • 235
  • 294
0

mylist = [['start', 'a', 'next'],['next','b','end'],['previous','c','start']]

Simplest way is dictionary comprehension

d = {i[0]: (i[1], i[2])for i in mylist}

you get d as the desired output

{'start': ('a', 'next'), 'next': ('b', 'end'), 'previous': ('c', 'start')}

with least time complexity time: 6 µs

kid
  • 153
  • 10