Neil
Neil

Reputation: 919

Add Values to Existing Entry in Dictionary

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

Answers (3)

Rohit Jain
Rohit Jain

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

dnozay
dnozay

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:

  • 2 tests have the same name?
  • the test results have more than 4 elements?

Upvotes: 0

mishik
mishik

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

Related Questions