Reputation: 987
I have this huge list ( mylist
) that contains strings like this:
>>> mylist[0]
'Akaka D HI -1 -1 1 1 1 -1 -1 1 1 1 1 1 1 1 -1 1 1 1 -1 1 1 1 1 1 -1 1 -1 -1 1 1 1 1 1 1 0 0 1 -1 -1 1 -1 1 -1 1 1 -1'
now, I want to take those 0, 1 and -1 and make a list with them, so I can make a list with the name at the first part of the string with the values of the list of 0, 1 and -1... so after some time I come up with this monstrosity
dictionary = {}
for x in range(len(mylist)-1):
dictionary.update({mylist[x].split()[0],[]}),[mylist[0].split()[k] for k in range(3,len(mylist[0].split()))]})
But when I try that out in the commandline, I get this error:
>>> for x in range(len(mylist)-1):
... dictionary.update({mylist[x].split()[0],[mylist[0].split()[k] for k in range(3,len(mylist[0].split()))]})
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: unhashable type: 'list'
Upvotes: 1
Views: 2840
Reputation: 1190
You could do it with regular expressions.
import re
mydict = {}
for x in mylist:
myname = re.search(r'^(.*?)(?= [-10])', x).group()
myentry = re.findall(r'-*\d', x)
mydict['myname'] = myentry
The first pattern starts at the beginning and matches any string until a space followed by a -
, 1
or 0
, to capture the name. The second pattern matches any number, preceded by any number (zero included) of -
, findall returns a list of all the pattern matches.
Upvotes: 0
Reputation: 103694
You could use a regex:
import re
st='Akaka D HI -1 -1 1 1 1 -1 -1 1 1 1 1 1 1 1 -1 1 1 1 -1 1 1 1 1 1 -1 1 -1 -1 1 1 1 1 1 1 0 0 1 -1 -1 1 -1 1 -1 1 1 -1'
dic={}
m=re.match(r'([a-zA-Z\s]+)\s(.*)',st)
if m:
dic[m.group(1)]=m.group(2).split()
result:
{'Akaka D HI': ['-1', '-1', '1', '1', '1', '-1', '-1', '1', '1', '1', '1', '1', '1', '1', '-1', '1', '1', '1', '-1', '1', '1', '1', '1', '1', '-1', '1', '-1', '-1', '1', '1', '1', '1', '1', '1', '0', '0', '1', '-1', '-1', '1', '-1', '1', '-1', '1', '1', '-1']}
Upvotes: 1
Reputation: 97918
One way to do this:
dictionary = {}
for x in mylist:
p = x.find('1')
if p > 0 and x[p-1] == '-': p -= 1
dictionary[x[0:p].strip()] = x[p:].split()
Upvotes: 2