Reputation: 919
I am starting out with a list like this
lists = [['test', '1', '-1', '0', '-1'],['test2', '0', '1', '0', '-1']
What I want to end up with is {'test': [1, -1, 0, -1], 'test2': [0, 1, 0, -1]}
So basically, I need to create a dictionary out of the lists. The values of the dictionary need to be integers and not strings.
This is my non-working code:
endResult = dict()
for x in lists:
for y in x:
endResult.update({x[0]:int(y)})
Upvotes: -1
Views: 120
Reputation: 213223
You can use dict
comprehension:
>>> lists = [['test', '1', '-1', '0', '-1'],['test2', '0', '1', '0', '-1']]
>>>
>>> endResult = { li[0]: map(int, li[1:]) for li in lists }
>>> endResult
{'test': [1, -1, 0, -1], 'test2': [0, 1, 0, -1]}
Upvotes: 2
Reputation: 24314
this should just work:
endResult = dict()
for x in lists:
testname, testresults = x[0], x[1:]
endResult[testname] = [int(r) for r in testresults]
what happens if:
Upvotes: 0
Reputation: 10003
endResult = {}
for x in lists:
endResult[x[0]] = [int(y) for y in x[1:]]
Example:
>>> lists = [['test', '1', '-1', '0', '-1'],['test2', '0', '1', '0', '-1']]
>>> endResult = {}
>>> for x in lists:
... endResult[x[0]] = [int(y) for y in x[1:]]
...
>>> endResult
{'test2': [0, 1, 0, -1], 'test': [1, -1, 0, -1]}
Upvotes: 1