Python分割值错误
我对python split()函数有问题。是否有人可以帮助我修复此错误,该错误会拆分字典的元素并逐行返回:Python分割值错误,python,Python,我对python split()函数有问题。是否有人可以帮助我修复此错误,该错误会拆分字典的元素并逐行返回: def lines_to_dict(lines): return_dict = {} for ll in lines: [key, value] = ll.split() return_dict[key] = value return return_dict 当我跑的时候 lines = ["the :1",
def lines_to_dict(lines):
return_dict = {}
for ll in lines:
[key, value] = ll.split()
return_dict[key] = value
return return_dict
当我跑的时候
lines = ["the :1", "and :2"]
print (lines_to_dict(lines))
在同一行中给我{“the”:“:1”,“and”:“:2”}
。但是我应该得到
the :1
and :2
我尝试使用[key,value]=ll.split(','),但它给了我一个错误
[key, value] = ll.split(",")
ValueError: need more than 1 value to unpack
您的函数工作正常,它返回一个已解析项的字典。如果要在单独的行上打印这些项目,则需要在字典中循环:
lines = ["the :1", "and :2"]
result = lines_to_dict(lines)
for key, value in result.items():
print(key, value)
您看到的是字典字符串表示法:
>>> result
{'and': ':2', 'the': ':1'}
>>> result['and']
':2'
>>> for key, value in result.items():
... print(key, value)
...
and :2
the :1
你对问题是什么感到困惑;您的代码可以创建一个字典,但是您正在抱怨Python打印字典的方式。您不能在“,”上拆分,因为这只是字典显示的一部分,它不在您的文本中!