Divino Divino -4 years ago 154
Python Question

Convert List to Dict

How do I convert this LIST data structure to DICTIONARY. I want it in a key/value format.

['FREQ=WEEKLY', 'INTERVAL=2', 'UNTIL=20170511T050000Z', 'BYDAY=MO,TU,WE,TH,FR,SA,SU', 'RDATE:20170224T060000Z', 'EXDATE:20170228T060000Z']

Answer Source

Just split the string and put them in 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

Output:

{'BYDAY': 'MO,TU,WE,TH,FR,SA,SU', 'INTERVAL': '2', u'RDATE': '20170224T060000Z', 'EXDATE': '20170228T060000Z', 'FREQ': 'WEEKLY', 'UNTIL': '20170511T050000Z'}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download