Skip to content
Advertisement

Python – Check if value is unique in dictionary of lists

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.

Advertisement

Answer

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]
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement