Skip to content
Advertisement

Creating dictionary from strings containing a specific letter

I’m trying to create a dictionary from a text file that contains test results.

The text file looks like this:

NETAPP-MIB::enclTempSensorsCurrentTemp.1 = STRING: 29C (84F) ambient, 36C (96F), 36C (96F), 36C (96F), 36C (96F), 36C (96F), 57C (134F), 37C (98F), 57C (134F), 44C (111F), 59C (138F), 40C (104F), 45C (113F), 58C (136F), 42C (107F)

My goal is to get all the results that contain a number with the letter C. But I manage to get only the first value

For example this is what I get:

{'TEST sensor num 0': '29C'}

This is my code:

import re

def get_names(ip):
    """Get the server name according the IP address"""
    names = {"TEST": "10.205.110.226", "TEST2": "10.205.111.216"}
    if ip in names.values():
        for key, val in names.items():
            if ip == val:
                return key
    else:
        return f"No Recognized unit {ip}"


def get_temps_servers():
    """ Return A dict mapping from sensor name to sensor value """
    result = {}
    count = 0
    with open("test.txt", "r") as newdata:
        text = newdata.read()
    for ip in online_server:
        name = get_names(ip)
        for c in re.findall(r"^.*?(d+C)", text, flags=re.M):
            result[f"{name} sensor num {count}"] = c
            count = count + 1
    print(result)
    return result


global online_netapp
online_server = ["10.205.110.226"]

get_temps_servers()

What I want to get is result like this example:

{'TEST sensor num 0': '29C', 'TEST sensor num 1': '36C', 'TEST sensor num 2': '36C'}

And will continue like this as long as there is a number with C.

What am I doing wrong?

Advertisement

Answer

Maybe this will nudge you in the right direction:

import json
import re

pattern = re.compile(r"d{2}C")
long_string = "NETAPP-MIB::enclTempSensorsCurrentTemp.1 = STRING: 29C (84F) ambient, 36C (96F), 36C (96F), 36C (96F), 36C (96F), 36C (96F), 57C (134F), 37C (98F), 57C (134F), 44C (111F), 59C (138F), 40C (104F), 45C (113F), 58C (136F), 42C (107F)"
d = {
    f"TEST sensor num {index}": temp
    for index, temp in enumerate(re.findall(pattern, long_string))
}

print(json.dumps(d, indent=2))

Output:

{
  "TEST sensor num 0": "29C",
  "TEST sensor num 1": "36C",
  "TEST sensor num 2": "36C",
  "TEST sensor num 3": "36C",
  "TEST sensor num 4": "36C",
  "TEST sensor num 5": "36C",
  "TEST sensor num 6": "57C",
  "TEST sensor num 7": "37C",
  "TEST sensor num 8": "57C",
  "TEST sensor num 9": "44C",
  "TEST sensor num 10": "59C",
  "TEST sensor num 11": "40C",
  "TEST sensor num 12": "45C",
  "TEST sensor num 13": "58C",
  "TEST sensor num 14": "42C"
}

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement