Question

There is a python list in the following format

mylist = [u'Name:', u'John', , u'Doe', u'Address:', u'Washington Street ',  u'Chicago']

There is ':' right at the end of keys, in this case is Name and Address. The new dict should be something like:

newdict = {
'Name': '["John", "Doe"]', 
'Address': '["Washington Street", "Chicago"]',
}
Was it helpful?

Solution

While not necessarily intuitive to use itertools.groupby for this, you can take advantage of how it works:

res = {}
for iskey, it in groupby(mylist, lambda s: s.endswith(':')):
    if iskey:
        for k in it:
            key = k[:-1]
            res[key] = []
    else:
        res[key].extend(it)

res
=> {u'Address': [u'Washington Street ', u'Chicago'], u'Name': [u'John', u'Doe']}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top