Home > OS >  Iterating over multiple (zipped) arrays in parallel and appending to dictionary
Iterating over multiple (zipped) arrays in parallel and appending to dictionary

Time:07-14

I have three arrays of that look something like this:

    [1,0,0,0,2,0,3,0,0,4,0,1,0,0,0,1]
    [2,0,0,0,0,0,2,0,0,3,0,0,0,1,0,1]
    [0,0,1,0,0,0,1,0,1,0,0,0,2,0,0,0]

Every number represents another value:

```
1 = "apple"
2 = "banana"
3 = "boat"
```

My goal is to merge them and place them as lists in dictionary keys 1:16 where each key represents an index in the array:

```
{0: ["apple","banana"] 1: [] 2: ["apple"] 3: [] 4 ["banana"]...} 
```

Now I've twisted my brain into a knot.


    multiarray = zip(a1,a2,a2)
    
    def arraymerger(zippedarrays):
        d = {}
        for i in range(16):
            d[f'{i}'] = []
            for a1, a2, a3 in wop:
                if a1 == 1 or a2 == 1 or a3 == 1:
                    d[f'{i}'].append('apple')
                elif a1 or a2 or a3 == 2:
                    d[f'{i}'].append('banana')
                elif a1 or a2 or a3 == 3:
                    d[f'{i}'].append('boat')
        return d
    
    merged_dict = arraymerger(multiarray)

The output I get is all the apples, bananas, and boats (and multiple instances of them) in the first key of the dictionary.

I know I'm probably looping over the wrong thing or using the wrong if statement but I'm going a bit nuts.

Can you please help me?

CodePudding user response:

Something like this:

a1 = [1,0,0,0,2,0,3,0,0,4,0,1,0,0,0,1]
a2 = [2,0,0,0,0,0,2,0,0,3,0,0,0,1,0,1]
a3 = [0,0,1,0,0,0,1,0,1,0,0,0,2,0,0,0]

items = {1: "apple", 2: "banana", 3: "boat", 4: "insert item here"}
zipped = zip(a1, a2, a3)

merged_dict = {i : [] for i in range(len(a1))}
for idx, z in enumerate(zipped):
    for z_index in z:
        if z_index != 0:
            merged_dict[idx].append(items[z_index])

print(merged_dict)

Output:

{0: ['apple', 'banana'], 1: [], 2: ['apple'], 3: [], 4: ['banana'], 5: [], 6: ['boat', 'banana', 'apple'], 7: [], 8: ['apple'], 9: ['insert item here', 'boat'], 10: [], 11: ['apple'], 12: ['banana'], 13: ['apple'], 14: [], 15: ['apple', 'apple']}

CodePudding user response:

a = [1,0,0,0,2,0,3,0,0,4,0,1,0,0,0,1]
b = [2,0,0,0,0,0,2,0,0,3,0,0,0,1,0,1]
c = [0,0,1,0,0,0,1,0,1,0,0,0,2,0,0,0]


anotherValueDict = {
    1: "apple",
    2: "banana",
    3: "boat",
    4: "some thing"
}

zippedArray = zip(a, b, c)

out = {i: [anotherValueDict[item] for item in items if item] for i, items in enumerate(zippedArray)}

can be better
out

{0: ['apple', 'banana'], 1: [], 2: ['apple'], 3: [], 4: ['banana'], 5: [], 6: ['boat', 'banana', 'apple'], 7: [], 8: ['apple'], 9: ['some thing', 'boat'], 10: [], 11: ['apple'], 12: ['banana'], 13: ['apple'], 14: [], 15: ['apple', 'apple']}
  • Related