Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Tuple splitting with dictionaries

This is the dictionary that I currently have.

d={'art1':{'poll1':{'v':10, 'i':9, 'r':9/10, 'prob': 0.9},'poll2':{'v':8, 'i':3, 'r':3/8, 'prob': 0.1}},
   'art2':{'poll1':{'v':11, 'i':4, 'r':4/11, 'prob': 0.4},'poll2':{'v':4, 'i':2, 'r':2/4, 'prob': 0.6}}
  }

And the output that I am looking for is the following:

{'art1': {'poll1': {'v': 10,
   'i': 9,
   'r': 0.9,
   'prob': 0.9,
   'position': (0, 0.9)},
  'poll2': {'v': 8, 'i': 3, 'r': 0.375, 'prob': 0.1, 'position': (0.9, 1.0)}},
 'art2': {'poll1': {'v': 11,
   'i': 4,
   'r': 0.36363636363636365,
   'prob': 0.4,
   'position': (0, 0.4)},
  'poll2': {'v': 4, 'i': 2, 'r': 0.5, 'prob': 0.6, 'position': (0.4, 0.6)}}}

I basically want the position to be an interval where we add their probabilities (prob).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I was able to come up with this chunk of code, but the position from poll2 does not start with the probability at the end of poll1 position.

for article, v in d.items():
    a=0
    print(d[article])
    print(v)
    for k,values in v.items():
        a+=values['prob']
        if k=='poll1':
            values['position']=(0,values['prob'])
        else:
            values['position']=(a,a+values['prob'])

The output for this is:

{'art1': {'poll1': {'v': 10,
   'i': 9,
   'r': 0.9,
   'prob': 0.9,
   'position': (0, 0.9)},
  'poll2': {'v': 8, 'i': 3, 'r': 0.375, 'prob': 0.1, 'position': (1.0, 1.1)}},
 'art2': {'poll1': {'v': 11,
   'i': 4,
   'r': 0.36363636363636365,
   'prob': 0.4,
   'position': (0, 0.4)},
  'poll2': {'v': 4, 'i': 2, 'r': 0.5, 'prob': 0.6, 'position': (1.0, 1.6)}}}

I was hoping to be able to do this with multiple polls, so I would really appreciate if it was a generalized answer. Thank you so much for your help, and if you have any other question or if what I explained isn’t clear please let me know.

>Solution :

Iterate over arts.

For each art create index_prob = 0

Then iterate over polls in this art and add prob to index_probs while also adding position key-value to poll values

for art, polls in d.items():
    index_prob = 0
    for poll, value in polls.items():
        value['position'] = (index_prob, index_prob + value['prob'])
        index_prob += value['prob']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading