Is there a way to check if a value is unique for a specific list, within a dictionary of lists? If yes, I would like to know in which key/list pair/s the value is present.
For example: {1: [3, 4, 5], 2: [4], 3: [5], 6: [3, 5, 9], 8: [3 ,8]}
I want to check if 3 is present in any of the other lists within the dictionary, besides 1: [3, 4, 5(compare it with all others). Since it is, then I must receive as a result 6 and 8, because these are the keys, which corresponding lists have this value.
CodePudding user response:
You can enter the value you are looking for and then loop over all the dictionaries to see if its in them.
Take this as pseudo code:
int val = 3
for(keys in mydict):
if(mydict.key.contains(val())
print(mydict.key)
You could also save the dictionaries in a list, so that you have a list of dicts with your corresponding value.
CodePudding user response:
Not entirely sure if this is what you meant but:
def unique(list1):
# initialize a null list:
unique_list = []
# traverse for all elements:
for x in list1:
# check if exists in unique_list or not
if x not in unique_list:
unique_list.append(x)
# printing the list:
for x in unique_list:
print(x, end=' ')
list1 = [10, 20, 10, 30, 40, 40]
print("the unique values from 1st list is")
unique(list1)
list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]
print("\nthe unique values from 2nd list is")
unique(list2)
This code will loops through all the values and ensure that they are not repeated.
CodePudding user response:
You could write some simple helper functions like so:
my_dict = {1: [3, 4, 5], 2: [4], 3: [5], 6: [3, 5, 9], 8: [3 ,8]}
def keys_containing_element(dict_of_lists: dict, element: int) -> list:
"""Return all keys in dict_of_list whose list contains element"""
return [key for key in dict_of_lists.keys() if element in dict_of_lists[key]]
def is_element_unique(dict_of_lists: dict, element: int) -> list:
"""Return true if element is in exactly one of the lists in dict_of_lists"""
return True if len(keys_containing_element(dict_of_lists, element)) == 1 else False
Now,
print(keys_containing_element(my_dict, 3))
print(is_element_unique(my_dict, 3))
print(keys_containing_element(my_dict, 9))
print(is_element_unique(my_dict, 9))
outputs
[1, 6, 8]
False
[6]
True
CodePudding user response:
Try this:
def find_n(nums, target, exception):
res = []
for n, nums_list in nums.items():
exception_key = [i for i in exception][0]
if n != exception_key and nums_list != exception[exception_key]:
if target in nums_list:
res.append(n)
return res
if __name__ == '__main__':
nums = {1: [3, 4, 5], 2: [4], 3: [5], 6: [3, 5, 9], 8: [3, 8]}
target = 3
exception = {1: [3, 4, 5]}
print(find_n(nums, target, exception))
Reuslt:
[6, 8]