简体   繁体   中英

Convert nested list of lists into a dictionary

I have an array of lists that I need to turn into a dictionary where the first element in each list is a key and the remaining elements are values corresponding to that key.

For example, the array:

 a=[[[1, 2, 4] [2, 1, 3, 5] [3, 2, 6]]
   [[4, 1, 5, 7] [5, 2, 4, 6, 8] [6, 3, 5, 9]]]

should look like:

 dict = {1:[2,4], 2:[1,3,5], 3:[2,6], 4:[1,5,7], 5:[2,4,6,8], 6:[3,5,9]}

While the object looks like a list of lists, it is actually an array created by this process:

 a = [[i] for i in range(1, 10)]
     swap = a[0]
     a[0] = None
     b = np.array(a)
     b[0] = swap
     b.shape = 3, 3

Then I looped through the array and appended numbers to the different list elements which is why the lists have expanded. Let me know if that's not clear!

Is there an easy way to loop through an array and create this? Thanks!

You can use nested dict comprehension with extended iterable unpacking :

>>> l = [[[1, 2, 4], [2, 1, 3, 5], [3, 2, 6]], [[4, 1, 5, 7], [5, 2, 4, 6, 8], [6, 3, 5, 9]]]
>>> {k: v for sub_l in l for k, *v in sub_l}
{1: [2, 4], 2: [1, 3, 5], 3: [2, 6], 4: [1, 5, 7], 5: [2, 4, 6, 8], 6: [3, 5, 9]}

Using generator to flatten the list,

a=[
     [[1, 2, 4], [2, 1, 3, 5], [3, 2, 6], ],
     [[4, 1, 5, 7], [5, 2, 4, 6, 8], [6, 3, 5, 9]],

   ]

def flat(a):
    for level1 in a:
        for level2 in level1:
            yield level2

result = {}
for l in flat(a):
    result[l[0]] = l[1:]

print result

Here is another solution based on @niemmi answer using itertools.chain() maybe more readable:

>>> import itertools
>>> l = [[[1, 2, 4], [2, 1, 3, 5], [3, 2, 6]], [[4, 1, 5, 7], [5, 2, 4, 6, 8], [6, 3, 5, 9]]]
>>> {k: v for k, *v in itertools.chain.from_iterable(l)}
{1: [2, 4], 2: [1, 3, 5], 3: [2, 6], 4: [1, 5, 7], 5: [2, 4, 6, 8], 6: [3, 5, 9]}

Now we got only one for loop by flatten the l list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM