Lists from a list based on specific key

Hi I am new in programming. I am having a problem. I don't know what is better solution for this issue. The problem is like this.. I have a list say,

list = ['a', '123', '643', 'b', '890', '234', '123', 'd', '432', '678' ]

So I want to make 3 lists or a json object, what actually possible please suggest better option. the idea is

list_a = ['123', '643']
list_b = ['890', '234', '123']
list_d = ['432', '678']

or,

list_ob = {"a": ["123", "643"], "b": ["890", "234", "123"], "d": ["432", "678"] }

Here a, b, d are only some specific character or can be words. Please help me out.

7 answers

  • answered 2018-07-12 07:20 Rakesh

    This is one approach using collections module.

    Ex:

    import collections
    l = ['a', '123', '643', 'b', '890', '234', '123', 'd', '432', '678' ]
    res = collections.OrderedDict()
    for i in l:
        if i.isalpha():
            res[i] = []
        else:
            res[res.keys()[-1]].append(i)
    print(res)
    

    Output:

    OrderedDict([('a', ['123', '643']), ('b', ['890', '234', '123']), ('d', ['432', '678'])])
    

    Or without modules

    l = ['a', '123', '643', 'b', '890', '234', '123', 'd', '432', '678', "z", "123" ]
    res = {}
    key = ""
    for i in l:
        if i.isalpha():
            res[i] = []
            key = i
        else:
            res[key].append(i)
    print(res)
    

  • answered 2018-07-12 07:22 Aemyl

    I can only come up with this:

    list_ = ['a', '123', '643', 'b', '890', '234', '123', 'd', '432', '678']
    list_ob = {}
    for item in list_:
        try:
            int(item)
            list_ob[last].append(item)
        except ValueError:
            last = item
            list_ob[item] = []
        except NameError:
            pass  # first item in the list is the string representation of a number
    

  • answered 2018-07-12 07:23 Frank AK

    It's easy to reach that, you just need to loop check if it's alpha and then pick up the alpha as key. something like the below:

    In [92]: key = ''
        ...: b = {}
        ...: a = ['a', '123', '643', 'b', '890', '234', '123', 'd', '432', '678' ]
        ...: for i in a:
        ...:   
        ...:     if i.isalpha():
        ...:         b[i]=[]
        ...:         key = i
        ...:     else:
        ...:         b[key].append(i)
    In [94]: b
    Out[94]: {'a': ['123', '643'], 'b': ['890', '234', '123'], 'd': ['432', '678']}
    

    To get your second expect result, just simple do it by:

    In [95]: b.values()
    Out[95]: [['123', '643'], ['890', '234', '123'], ['432', '678']]
    

  • answered 2018-07-12 07:29 Lorran Sutter

    This json object you referred to is called dictionary in python and in many others programming languages. It is an structure where we have a key and a values associated with it.

    In this case it is easier to deal with a dictionary. Let's create an empty dictionary first:

    d = dict()
    

    Then, you going to create an for loop to fill this dictionary:

    current_key = ""
    
    for e in l:
        if e.isalpha(): # If is a letter
            current_key = e
            d[current_key] = [] # Create an empty list as value
        else:
            d[current_key].append(e) # Append value
    

    Result:

    {'a': ['123', '643'], 'b': ['890', '234', '123'], 'd': ['432', '678']}
    

  • answered 2018-07-12 07:31 Alex Pshenko

    Defaultdict seems like good way to go:

    from collections import defaultdict
    def split_list(l):
        res = defaultdict(list)
        current_key = ''
        for el in l:
            if el.isalpha():
                current_key = el
            elif current_key:
                res[current_key].append(el)
        return res
    

  • answered 2018-07-12 07:37 aman5319

    Here is the solution

    {x[0]:x[1].split() for x in re.findall(r"([a-z])([\s*\d+]*)" , " ".join(list))}
    

    {'a': ['123', '643'], 'b': ['890', '234', '123'], 'd': ['432', '678']}

  • answered 2018-07-12 15:56 Ajax1234

    You can use itertools.groupby:

    import itertools
    l = ['a', '123', '643', 'b', '890', '234', '123', 'd', '432', '678' ]
    _t = [list(b) for _, b in itertools.groupby(l, key=lambda x:x.isdigit())]
    final_result = {_t[i][0]:_t[i+1] for i in range(0, len(_t), 2)}
    

    Output:

    {'a': ['123', '643'], 'b': ['890', '234', '123'], 'd': ['432', '678']}