Search code examples
pythonlistdictionaryprobabilitylogarithm

make log operations between a dictionary and a list of dictionaries


Hello I am looking to do find out this:

Assume I have this.

a= {'OCC': 6, 'FFR': 90, 'DTY': 3139, 'UTY': 1861, 'VGY': 2175, 'DGG': 364, 
    'CCG': 37, 'OPTY': 80, 'SET': 666, 'WEK': 82, 'XAU': 56, 'ROD': 38, 'PLS': 206, 'DAFF': 2, 'C': 2}

b= [{'key': 'OCC', 'count': 3615, 'prob': 0}, 
    {'key': 'FFR', 'count': 408, 'prob': 0}, 
    {'key': 'DTY', 'count': 915, 'prob': 0}, 
    {'key': 'UTY', 'count': 652, 'prob': 0}, 
    {'key': 'VGY', 'count': 365, 'prob': 0}, 
    {'key': 'UTY', 'count': 589, 'prob': 0}, 
    {'key': 'DGG', 'count': 573, 'prob': 0}, 
    {'key': 'DTY', 'count': 75, 'prob': 0}, 
    {'key': 'UTY', 'count': 148, 'prob': 0}, 
    {'key': 'UTY', 'count': 116, 'prob': 0}, 
    {'key': 'CCG', 'count': 7503, 'prob': 0}]

I would like to know how I could possibly get something like this: if the key in a is present in b, then do log(value of b) - log(value of a). Then possibly save it in the key 'prob'. (For this example let's consider the first element of dictionary a: key OCC is present in the first dictionary of list b. I am looking to find out how can I do it throughout all the list b and update every prob key in the dictionaries inside b)

So I would get something like this: log(3615)-log(6)=6.401087665364811 so prob in the first dictionary of list b should update to:

{'key': 'OCC', 'count': 3615, 'prob':6.401087665364811 }


Solution

  • If a and b are your inputs from question:

    from pprint import pprint
    from math import log
    
    for d in b:
        if d["key"] in a:
            d["prob"] = log(d["count"]) - log(a[d["key"]])
        
    pprint(b)
    

    A bit more on how this works, first it gets each dictionary, and for each dictionary, checks if the d["key"] (the key that should be in a) is in a. If so, it gest the d["count"] which is the count for that dict, calculates the log using the math log package, and also calculates the log of a[d["key"]] which is the value of a[<key stored in b>]. Then it subtracts both and assigns that to d["prob"]

    Prints:

    [{'count': 3615, 'key': 'OCC', 'prob': 6.401087665364811},
     {'count': 408, 'key': 'FFR', 'prob': 1.5114575040738965},
     {'count': 915, 'key': 'DTY', 'prob': -1.232735491566432},
     {'count': 652, 'key': 'UTY', 'prob': -1.0488246947155977},
     {'count': 365, 'key': 'VGY', 'prob': -1.7848865899402933},
     {'count': 589, 'key': 'UTY', 'prob': -1.1504430729906643},
     {'count': 573, 'key': 'DGG', 'prob': 0.45373184907799935},
     {'count': 75, 'key': 'DTY', 'prob': -3.7341714433056428},
     {'count': 148, 'key': 'UTY', 'prob': -2.531656982878136},
     {'count': 116, 'key': 'UTY', 'prob': -2.7752790655358863},
     {'count': 7503, 'key': 'CCG', 'prob': 5.3121403069015045}]