Search code examples
pythonloopsdefaultdict

searching for a specific element in default dictionary PYTHOn


My dict:

expiry_strike = defaultdict(<type 'list'>, {'2014-02-21': [122.5], '2014-01-24': [123.5, 122.5, 119.0, 123.0]})
expiry_value = defaultdict(<type 'list'>, {'2014-02-21': [-100], '2014-01-24': [-200, 200, 1200, 200]})

My question :

I want to run a loop which finds the common element and in expiry_strike ( 122.5 in this case ),

and if a common element is found,

then I would like to add the values in expiry_value . ( here i want to add -100 + 200 )


Solution

  • I am going to show you how you can find the most common element, the rest you should handle yourself.

    There is this nice library called collections which has a Counter class in it. Which counts each element in an iterable and stores them in a dictionary with the keys are the items and the values are the counts.

    from collections import Counter
    
    expiry_strike = {'2014-02-21': [122.5], '2014-01-24': [123.5, 122.5, 119.0, 123.0]}
    
    for values in expiry_strike.values():
        counts = Counter(values)
        print max(counts , key=lambda x: counts[x])
    
        # key=lambda x: counts[x] says to the max function
        # to use the values(which are the counts) in the Counter to find the max,
        # rather then the keys itself.
        # Don't confuse these values with the values in expiry_strike
    

    This finds the most common element for all different keys in expiry_strike. If you want to find the most common element using all the values in expiry_strike you have to combine the lists in expiry_strike.values().