WhyOnEarth
WhyOnEarth

Reputation: 13

Python: Turn a 2D numpy array into a dictionary

consider I have an array like:

c = [["a","b","a"],[1,2,3]]

Now I need to combine those two parts and I want to turn this into a dictionary, which counts how often a combination occurs(the values are the number of occurances). It should look something like this:

combinations = {("a",1):1, ("b",2):1, ("a",3):1)}

I am a total beginner and have some approaches like:

(c[0][0],[-1][0]),(c[0][1],[-1][1]),...

etc. for creating the pairs I need, but this is not very useful in case my array is of different size(both parts should stay the same size though). Plus I don't know how to put the number of occurances as values.

Any help is highly appreciated!

Upvotes: 1

Views: 2595

Answers (1)

Michael
Michael

Reputation: 28

You can use zip to combine the 2 sublists and count to count specific elements in the list.

    >>> c = [['a','b','a','a'],[1,2,3,1]]
    >>> pairs = zip(c[0],c[1])
    >>> pairs
    [('a', 1), ('b', 2), ('a', 3), ('a', 1)]

    >>> result = {i: pairs.count(i) for i in pairs}
    >>> result
    {('a', 1): 2, ('b', 2): 1, ('a', 3): 1}

The last command uses Dict Comprehension.

Upvotes: 1

Related Questions