Mee Seong Im Mee Seong Im - 6 months ago 7
Python Question

Creating a dictionary whose keys give multiplicities of the values occurring in an array of an array

I have this:

array1 = [[1,2,3],[1,2,3],[2,1,3],[2,1,3],[1,-2,3]]
array2 = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[0,2,3],[2,1,3]]


and want to create this:

multiArray1 = {[1,2,3]:2, [2,1,3]:2}
multiArray2 = {[1,2,3]:4, [2,1,3]:1}


Question: I am trying to make multiArray1 and multiArray2 as dictionaries containing the same values but the keys give the number of times these values occur in array1 and array2, respectively.

I am not sure what to change in my code. Any help would be greatly appreciated. Thanks.

from collections import defaultdict

array1 = [[1,2,3],[1,2,3],[2,1,3],[2,1,3],[1,-2,3]]
array2 = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[0,2,3],[2,1,3]]

def f(arrA,arrB):
multiArray1 = {}
multiArray2 = {}

intersect = set(map(tuple,arrA)).intersection(map(tuple,arrB))
print(set(map(tuple,arrA)).intersection(map(tuple,arrB)))

for i in intersect:
multiArray1.update({i:0})
multiArray2.update({i:0})
print(multiArray1)
print(multiArray2)

multipleArray1 = {}
multipleArray2 = {}

for i in intersect:
for j in range(len(arrA)):
if str(tuple(arrA[j])) in set(intersect):
multiArray1[tuple(arrA[j])].append(j)
print(multiArray1)

multipleArray1 = defaultdict(list)
for key, value in multipleArray1:
multipleArray1[i].append(j)
print(multipleArray1)

for j in range(len(arrB)):
if str(tuple(arrB[j])) in set(intersect):
multiArray2[tuple(arrB[j])].append(j)

multipleArray2 = defaultdict(list)
for key, value in multipleArray2:
multipleArray2[i].append(j)
print(multipleArray2)

print(multiArray1)
print(multiArray2)

f(array1,array2)


The output you get from the above code is this:

{(2, 1, 3), (1, 2, 3)}
{(2, 1, 3): 0, (1, 2, 3): 0}
{(2, 1, 3): 0, (1, 2, 3): 0}
{(2, 1, 3): 0, (1, 2, 3): 0}
{(2, 1, 3): 0, (1, 2, 3): 0}

Answer

The trick is, convert them to a string before you make them a key of a dict, because you can not have list as key for a dictionary.

dct1 = {}
dct2 = {}
array1 = [[1,2,3],[1,2,3],[2,1,3],[2,1,3],[1,-2,3]]
array2 = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[0,2,3],[2,1,3]]

for x in array1:
    cnt = array1.count(x)
    dct1[str(x)] = cnt #here str(x) convert the list to string
for x in array2:
    cnt = array2.count(x)
    dct2[str(x)] = cnt #again here


print (dct1)
print (dct2)

Output

>>> 
{'[1, 2, 3]': 2, '[1, -2, 3]': 1, '[2, 1, 3]': 2}
{'[1, 2, 3]': 4, '[2, 1, 3]': 1, '[0, 2, 3]': 1}
>>> 
Comments