Home > Enterprise >  How do I access nested values within lists and dictionaries to get data?
How do I access nested values within lists and dictionaries to get data?

Time:11-09

I'm trying to make a script that would read the CPU temperature and automatically shut down processes if it starts getting too hot. I have used psutil but I don't know how to get the value from there. This is what psutil.sensors_temperatures() output gives along with a bunch of

RuntimeWarning: ignoring FileNotFoundError.

{
'acpitz': [
   shwtemp(
      label='', 
      current=60.0, 
      high=103.0, 
      critical=103.0)
], 
'pch_cannonlake': [
    shwtemp(
       label='', 
       current=53.0,
       high=None, 
       critical=None)], 
'coretemp': [
    shwtemp(
       label='Package id 0', 
       current=60.0, high=100.0, 
       critical=100.0
    ), 
    shwtemp(
       label='Core 0', 
       current=59.0, 
       high=100.0, 
       critical=100.0
    ), 
    shwtemp(
       label='Core 1',
       current=59.0,
       high=100.0, 
       critical=100.0
    ), 
    shwtemp(
        label='Core 2', 
        current=60.0, 
        high=100.0, 
        critical=100.0), 
    shwtemp(
        label='Core 3', 
        current=57.0, 
        high=100.0, 
        critical=100.0)
], 
'iwlwifi_1': [
    shwtemp(
       label='', 
       current=49.0, 
       high=None, 
       critical=None
    )
]
}

How do I access the current value in "coretemp"? Isn't that the main one that shows CPU temperature? Or is it "acpitz"?

CodePudding user response:

You have a dictionary of lists containing psutil._common.shwtemp objects.

A quick look at the psutil source shows that those are actually namedtuple:

# psutil/_common.py
shwtemp = namedtuple(
    'shwtemp', ['label', 'current', 'high', 'critical'])

So, you can simply do:

# core number 0, current temperature
d['coretemp'][0].current
  • Related