pythonpython-3.xlistdictionarypyscripter

Convert a list of random keys and values to a dictonary


Suppose keys are represents by kn and values are represented by vn.

I have a list of keys and values like my_list_1 = [k1,v1,v2,v3,k2,v4,v5,k3,v6,v7,v8,v9,k4,v10]

Keys can be in repeated too in the list like my_list_2 = [k1,v1,v2,v3,k2,v4,v5,k3,v6,v7,v8,v9,k2,v10]

All the values which are followed by a particular key belongs to that key. For instance in my_list_1; v1,v2,v3 belongs to k1; v4,v5 belongs to k2 ; v6,v7,v8,v9 belongs to k3 and v10 belongs to k4. Therefore final dictionary would look like-

{
   k1: [v1,v2,v3] ,
   k2: [v4,v5] ,
   k3: [v6,v7,v8,v9],
   k4: [v10]
}

Similarly in case of my_list_2 it would be:

{
   k1: [v1,v2,v3] ,
   k2: [v4,v5,v10] ,
   k3: [v6,v7,v8,v9]
}

How can I convert this kind of list in the required dictionary?

Note: I already have functions to identify whether a particular item in list is a key or a value. Let's call these functions as isKey() and isValue().

isKey() returns True if an item is a key else returns False

isValue() returns True if an item is a value else returns False


Solution

  • Not sure if this can be done in a more pythonic way, but here is a loop that ought to do it. This assumes that a key will always directly precede all of its items and all of its items precede the next key.

    def my_list_to_dict(my_list):
        my_dict = {}
        my_key = None
        my_values = []
        for item in my_list:
            if isKey(item):
                if my_key != None:
                    my_dict[my_key] = my_values
                my_key = item
                my_values = []
            elif isValue(item):
                my_values.append(item)
        return my_dict