Home > Blockchain >  How do I create an object out of this 2d list and should I use a different data structure?
How do I create an object out of this 2d list and should I use a different data structure?

Time:03-17

So I have a 2d list that looks like this:

values = 
[['vatlinnas1', '2443632E4D9AB666', 'vatlinnas1_2443632E4D9AB666', 'server', 'vatlinnas1', 'Sat-Oct-26-16:42:19-2019'], 
['vatlinnas2', '2443632E4D9AB667', 'vatlinnas2_2443632E4D9AB667', 'server', 'vatlinnas2', 'Thu-May-06-15:35:50-2021'], 
['vattest01', '25000019C8AC330E726F00DDB0000000019C8', 'vattest01_25000019C8AC330E726F00DDB0000000019C8', 'server', 'vattest01', 'Wed-Mar-08-19:49:08-2023']]```

The data is in this order: common name, serial, cert_name, type(always "Server"), ca, expiration date

I am confused about how to use this data to populate an object. I'm actually not sure if I should be using a dictionary, a class, or something else. Ideally I would want my new data structure to look something like this(below) and I should be able to generate more instances of this class/object in a loop or through some sort of method.

class Item:
        def __init__(self, common_name, serial, ca, cert_name, thetype, ca, expirationDate):
                self.common_name = common_name
                self.serial = serial
                self.cert_name = cert_name
                self.thetype = "SERVER"
                self.ca = "ALWAYS_THE_SAME"
                self.expirationDate = expirationDate

I have a loop here but I'm not sure how to generate more instances of this class

for i in range(len(values)):
        for x in range(len(values[i])):
                print("i i : "   str( values[i][x]))

CodePudding user response:

Perhaps a dataclass?

from dataclasses import dataclass

values = [
    ['vatlinnas1', '2443632E4D9AB666', 'vatlinnas1_2443632E4D9AB666', 'server', 'vatlinnas1', 'Sat-Oct-26-16:42:19-2019'], 
    ['vatlinnas2', '2443632E4D9AB667', 'vatlinnas2_2443632E4D9AB667', 'server', 'vatlinnas2', 'Thu-May-06-15:35:50-2021'], 
    ['vattest01', '25000019C8AC330E726F00DDB0000000019C8', 'vattest01_25000019C8AC330E726F00DDB0000000019C8', 'server', 'vattest01', 'Wed-Mar-08-19:49:08-2023']
]


@dataclass
class Thingy:
    common_name: str
    serial: str
    cert_name: str
    thingy_type: str
    ca: str
    expiration_date: str

thingies = [Thingy(*fields) for fields in values]

  • Related