PyRoot: filling dictionary with histograms

Consider this example:

#! /usr/bin/env python                                                                                                                                                                                     
import ROOT

dictio = {}
N = 3
for ind in range(0, N):
    key = ROOT.TString("key_{}".format(ind))
    H = ROOT.TH1F(key.Data(), "h", 4, 0.0, 3.0)
    r = ROOT.TRandom(0)
    H.FillRandom("gaus", r.Integer(600))
    dictio[key] = H
    print "key %s id %s integral %f" % (key, hex(id(dictio[key])), H.Integral())
print "*****"
for key in dictio:
    print "key %s id %s integral %f" % (key, hex(id(dictio[key])), H.Integral())

The output is:

key key_0 id 0x7f2da76fa530 integral 228.000000
key key_1 id 0x7f2da76fa830 integral 116.000000
key key_2 id 0x7f2da76fa8f0 integral 7.000000
*****
key key_2 id 0x7f2da76fa8f0 integral 7.000000
key key_0 id 0x7f2da76fa530 integral 7.000000
key key_1 id 0x7f2da76fa830 integral 7.000000

Why is the integral of all histograms in the dictionary equal to the integral of the last histogram inserted?


Please read tips for efficient and successful posting and posting code

ROOT Version: Not Provided
Platform: Not Provided
Compiler: Not Provided


Hey @Viesturs,

Over here I believe the last histogram object you make has the name “H”, and even though you iterate through the dictionary and print its different keys, you never really reference each key’s histogram to print the integral - you are still calling the last histogram you made. To access the histogram for each key, then you would have to do this:

dictio[key].Integral()

This will get the histogram for the key you want. So maybe change your code to:

for key in dictio:
    print "key %s id %s integral %f" % (key, hex(id(dictio[key])), dictio[key].Integral())

Regards,
Diyon

1 Like

What an oversight :face_with_hand_over_mouth:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.