How to check the entry of a key in the dictionary value? Any length of the dictionary When I punched my key was checked in all the values ​​of the dictionary. Example

>>> print(dic) {1: [1, 5], 2: [1, 2], 3: [3, 4], 4: [3, 4], 5: [1, 5]} >>> for items in dic.keys(): for i in dic.values(): print(items, i) 1 [1, 5], 1 [1, 2], 1 [3, 4], 1 [3, 4], 1 [1, 5], 2 [1, 5], 2 [1, 2], 2 [3, 4], 2 [3, 4], 2 [1, 5] 

Next with 3, 4, and 5 is the same thing. I need only a verification key -> key value, not a key -> KEY value

I am interested in the output of the key and the values ​​in which this key is included. for the unit should output 1 [1, 5], 1 [1, 2] .

    1 answer 1

    Just before printing in a nested loop, check that the key is in the value: if key in value: ..

    If the values ​​in a given dictionary can be repeated, then in order not to print the same pairs (ключ, значение) several times, you can remove duplicate values ​​using set() :

     values = set(map(tuple, dic.values())) # remove duplicates for key in dic: for value in values: if key in value: print(key, list(value)) 

    Result

     1 [1, 2] 1 [1, 5] 2 [1, 2] 3 [3, 4] 4 [3, 4] 5 [1, 5] 

    This is a cubic algorithm O(n*n*m) , where n size of the dictionary, and m characterizes the size of the lists.

    You can get a quadratic algorithm O(n*m + n*n) (ignoring the steps for print() ):

     values = {frozenset(v): v for v in dic.values()} # remove duplicates for key in dic: for value_set in values: if key in value_set: print(key, values[value_set]) 

    The conclusion in this case is the same. In general, this algorithm ignores the order of numbers and repetitions within values ​​(if there is both [1, 2] and [2, 1] or [1,2,2] in dictionary values, then only one of them is output).