在Python中将字符串转换为列表或字典

时间:2013-10-20 17:36:41

标签: python

我需要打破对值的线条并将其转换为列表或dictonary。有没有人知道在Python中使用这种方法的简单方法?

由此:

1
Petrov
2
Ivanov
3
Sidorov

["1", "Petrov"], ["2", "Ivanov"], ["3", "Sidorov"]

或dictonary:

{"1": "Petrov", "2": "Ivanov", "3": "Sidorov"}

4 个答案:

答案 0 :(得分:3)

>>> strs = """1                            
Petrov
2
Ivanov
3
Sidorov"""
>>> dict(zip(*[iter(strs.splitlines())]*2))
{'2': 'Ivanov', '3': 'Sidorov', '1': 'Petrov'}

相关:How does zip(*[iter(s)]*n) work in Python?

答案 1 :(得分:0)

此代码将返回字典:

inp = open("file")
d = dict()
k = list()
v = list()
for line in inp:
    if line.strip("\n").isdigit():
        k.append(line.strip("\n"))
    else:
        v.append(line.strip("\n"))
print dict(zip(k,v))

答案 2 :(得分:0)

通过操纵列表中的奇数和偶数项,为hcwhsa的解决方案添加一点点扭曲:

>>> s = "1\nPetrov\n2\nIvanov\n3\nSidorov"
>>> dict(zip(s.split("\n")[::2], s.split("\n")[1::2]))
{'1': 'Petrov', '3': 'Sidorov', '2': 'Ivanov'}

请参阅Shortest way to slice even/odd lines from a python array?

答案 3 :(得分:0)

>>> strs = """1                            
Petrov
2
Ivanov
3
Sidorov"""
>>> i = iter(strs.split())
>>> {item: i.next() for item in i}
{'1': 'Petrov', '3': 'Sidorov', '2': 'Ivanov'}

>>> i = iter(strs.split())
>>> [[item, i.next()] for item in i]
[['1', 'Petrov'], ['2', 'Ivanov'], ['3', 'Sidorov']]