Python 向字典中的现有条目添加值

Python 向字典中的现有条目添加值,python,Python,我从这样的清单开始 lists = [['test', '1', '-1', '0', '-1'],['test2', '0', '1', '0', '-1'] 我想要的结果是{'test':[1,-1,0,-1],'test2':[0,1,0,-1]} 所以基本上,我需要从列表中创建一个字典。字典的值必须是整数而不是字符串 这是我的非工作代码: endResult = dict() for x in lists: for y in x: endResult.updat

我从这样的清单开始

lists = [['test', '1', '-1', '0', '-1'],['test2', '0', '1', '0', '-1']
我想要的结果是
{'test':[1,-1,0,-1],'test2':[0,1,0,-1]}

所以基本上,我需要从列表中创建一个字典。字典的值必须是整数而不是字符串

这是我的非工作代码:

endResult = dict()
for x in lists:
    for y in x:
        endResult.update({x[0]:int(y)})
例如:

>>> 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]}
您可以使用:

这应该是可行的:

endResult = dict()
for x in lists:
    testname, testresults = x[0], x[1:]
    endResult[testname] = [int(r) for r in testresults]
如果:

  • 2个测试有相同的名称
  • 测试结果有4个以上的元素
>>> 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]}
endResult = dict()
for x in lists:
    testname, testresults = x[0], x[1:]
    endResult[testname] = [int(r) for r in testresults]