I want to check if a dictionary already exists in a group of lists. Without the use of any()
in the if-statement
, I received the following error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
But then when I do make use of the any()
, the following error arises:
TypeError: 'bool' object is not iterable
I don't know where I'm going wrong. Any help or guidance on this would be much appreciated.
import numpy as np
compile = []
MY_LIST = [[['Mon'], np.array([4,2,1,3]), ['text'], ['more_text', 0.1]], [['Mon'], np.array([4,2,1,3]), ['text'], ['more_text', 0.1]], [['Tues'], np.array([3, 1, 2, 4]), ['text2'], ['more_text2', 0.2]]]
for group in MY_LIST:
my_dict = {'A': group[0], 'B': group[1], 'C': group[2],
'D': group[3]}
if any(my_dict not in compile): # Error here
compile.append(my_dict)
print (compile)
The expected output should be:
[{'A': ['Mon'], 'B': array([4, 2, 1, 3]), 'C': ['text'], 'D': ['more_text', 0.1]}, {'A': ['Tues'], 'B': array([3, 1, 2, 4]), 'C': ['text2'], 'D': ['more_text2', 0.2]}]
CodePudding user response:
The issue boils down to the fact that you can't directly compare two numpy
arrays using ==
alone, unlike most types. You need to define a custom function to compare two values in the dictionaries to handle the different types:
import numpy as np
def compare_element(elem1, elem2):
if type(elem1) != type(elem2):
return False
if isinstance(elem1, np.ndarray):
return (elem1 == elem2).all()
else:
return elem1 == elem2
result = []
MY_LIST = [
[['Mon'], np.array([4,2,1,3]), ['text'], ['more_text', 0.1]],
[['Mon'], np.array([4,2,1,3]), ['text'], ['more_text', 0.1]],
[['Tues'], np.array([3, 1, 2, 4]), ['text2'], ['more_text2', 0.2]]
]
for group in MY_LIST:
elem_to_append = dict(zip(['A', 'B', 'C', 'D'], group))
should_append = True
for item in result:
if all(compare_element(item[key], elem_to_append[key]) for key in item):
should_append = False
break
if should_append:
result.append(elem_to_append)
print(result)