-4

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'] 
Divino
  • 47
  • 1
  • 6
  • 2
    Possible duplicate of [Convert a list to a dictionary in Python](http://stackoverflow.com/questions/4576115/convert-a-list-to-a-dictionary-in-python) – aavrug Feb 27 '17 at 04:11
  • 1
    So some of your elements are deliminated by `=` but others by `:`? – Paul Rooney Feb 27 '17 at 04:11
  • your list didn't have similar elements, some have = and other have :, so on which symbol you need to split. – Rakesh Kumar Feb 27 '17 at 04:13
  • 1
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ](http://stackoverflow.com/tour) and [How to Ask](http://stackoverflow.com/questions/how-to-ask). – TigerhawkT3 Feb 27 '17 at 04:14
  • TigerhawkT3, Thanks for that tip. I should have posted a code. I will do that next time. – Divino Feb 27 '17 at 04:39

3 Answers3

1

Here is sample code with work with both symbols = and ::-

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'}
Rakesh Kumar
  • 4,319
  • 2
  • 17
  • 30
1

The easiest way to split on multiple delimiters is probably 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)
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
0

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'}
McGrady
  • 10,869
  • 13
  • 47
  • 69