Python:在列表中拆分字符串并形成字典

时间:2017-07-20 17:47:07

标签: python list dictionary

我有一个字符串列表如下:

e = ['Website: Alabama Office of the Attorney General',
 'Toll Free: 1-800-392-5658',
 'Website: State Banking Department',
 'Toll Free: 1-866-465-2279',
 'Website: Department of Insurance',
 'Phone Number: 334-241-4141',
 'Website: Securities Commission',
 'Phone Number: 334-242-2984',
 'Website: Public Service Commission',
 'Toll Free: 1-800-392-8050']

我希望通过将字符串拆分为"来形成字典:"并在列表中形成每两个元素的字典,如:

e = [{'Website': 'Alabama Office of the Attorney General',
 'Toll Free': '1-800-392-5658'},
 {'Website': 'State Banking Department',
 'Toll Free': '1-866-465-2279'},
 {'Website': 'Department of Insurance',
 'Phone Number': '334-241-4141'},
 {'Website': 'Securities Commission',
 'Phone Number': 334-242-2984'},
 {'Website': 'Public Service Commission',
 'Toll Free': '1-800-392-8050'}] 

一如既往地感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

如果你想要一个字典每两行。您可以使用:

ei = iter(e)
[{k:v for k,v in (x.split(':',1) for x in xs)} for xs in zip(ei,ei)]

产生

>>> [{k:v for k,v in (x.split(':',1) for x in xs)} for xs in zip(ei,ei)]
[{'Website': ' Alabama Office of the Attorney General', 'Toll Free': ' 1-800-392-5658'}, {'Website': ' State Banking Department', 'Toll Free': ' 1-866-465-2279'}, {'Website': ' Department of Insurance', 'Phone Number': ' 334-241-4141'}, {'Website': ' Securities Commission', 'Phone Number': ' 334-242-2984'}, {'Website': ' Public Service Commission', 'Toll Free': ' 1-800-392-8050'}]

或更好的格式化:

>>> [{k:v for k,v in (x.split(':',1) for x in xs)} for xs in zip(ei,ei)]
[{'Website': ' Alabama Office of the Attorney General', 'Toll Free': ' 1-800-392-5658'},
 {'Website': ' State Banking Department', 'Toll Free': ' 1-866-465-2279'},
 {'Website': ' Department of Insurance', 'Phone Number': ' 334-241-4141'},
 {'Website': ' Securities Commission', 'Phone Number': ' 334-242-2984'},
 {'Website': ' Public Service Commission', 'Toll Free': ' 1-800-392-8050'}]

如果您想删除值中的空格,我们可以使用strip()

ei = iter(e)
[{k:v.strip() for k,v in (x.split(':',1) for x in xs)} for xs in zip(ei,ei)]

如果每个字典 n ,我们可以使用:

n = 2
ei = iter(e)
[{k:v for k,v in (x.split(':',1) for x in xs)} for xs in zip(*((ei,)*n))]

答案 1 :(得分:-1)

# Assumption :  Total 2*n entries are present
ans = []
for i in xrange(0, len(e), 2):
    website = e[i].strip().split(':')
    toll = e[i+1].strip().split(':')
    ans.append({website[0]:website[1], toll[0]:toll[1]})