如何将此LIST数据结构转换为DICTIONARY。我想要一个键/值格式。
['FREQ=WEEKLY', 'INTERVAL=2', 'UNTIL=20170511T050000Z', 'BYDAY=MO,TU,WE,TH,FR,SA,SU', 'RDATE:20170224T060000Z', 'EXDATE:20170228T060000Z']
答案 0 :(得分:1)
以下是包含符号=
和:
的示例代码: -
a = ['FREQ=WEEKLY', 'INTERVAL=2', 'UNTIL=20170511T050000Z', 'BYDAY=MO,TU,WE,TH,FR,SA,SU', 'RDATE:20170224T060000Z', 'EXDATE:20170228T060000Z']
print {spi[0]:spi[1] for spi in [item.split("=") if "=" in item else item.split(":") for item in a]}
output: {'BYDAY': 'MO,TU,WE,TH,FR,SA,SU', 'EXDATE': '20170228T060000Z', 'FREQ': 'WEEKLY', 'INTERVAL': '2','RDATE': '20170224T060000Z','UNTIL': '20170511T050000Z'}
答案 1 :(得分:1)
分割多个分隔符的最简单方法可能是re.split
。
import re
data = ['FREQ=WEEKLY', 'INTERVAL=2', 'UNTIL=20170511T050000Z', 'BYDAY=MO,TU,WE,TH,FR,SA,SU', 'RDATE:20170224T060000Z', 'EXDATE:20170228T060000Z']
result = dict(re.split('=|:', line, 1) for line in data)
答案 2 :(得分:0)
只需拆分字符串并将它们放入dict:
l=['FREQ=WEEKLY', 'INTERVAL=2', 'UNTIL=20170511T050000Z', 'BYDAY=MO,TU,WE,TH,FR,SA,SU', 'RDATE:20170224T060000Z', 'EXDATE:20170228T060000Z']
d={}
for i in l:
if "=" in i:
d[i.split("=")[0]]=i.split("=")[1]
elif ":" in i:
d[i.split(":")[0]] = i.split(":")[1]
else:
pass
print d
输出:
{'BYDAY': 'MO,TU,WE,TH,FR,SA,SU', 'INTERVAL': '2', u'RDATE': '20170224T060000Z', 'EXDATE': '20170228T060000Z', 'FREQ': 'WEEKLY', 'UNTIL': '20170511T050000Z'}