2

I have a list which has some dictionaries to be bulk uploaded. I need to check if elements of list can be cast to a custom object(as below). Is there any elegant way to do it like type comparison?

This is my model

class CheckModel(object):

    def __init__(self,SerialNumber,UID, Guid = None,Date = None):
        self.SerialNumber = SerialNumber
        self.UID = UID
        self.Guid = str(uuid.uuid4()) if Guid is None else Guid
        self.Date = datetime.now().isoformat() if Date is None else Date

And this is my test data. How can I cast only first element(because first element is the only correct one.) of this list into CheckModel object?

test = [{
        "Guid":"d0c035a7-0e01-4a37-8fe9-251fb5633fc9",
        "SerialNumber":"1716154A",
        "UID":"F13BDB3B",
        "Date":"2019-12-03T13:50:19.882Z"

    },
    {
        "Guid":"d0585-0e01-4a47-8fe9-251245f33fc9",
        "SerialNumber":"1716154A",
        "Date":"2019-12-03T13:50:19.882Z"
    },
    {
        "Guid":"12414a7-0e01-4a47-8fe9-251245f33fc9",
        "SerialNumber":"1716154A",
        "UID":"F13BDB3B",
        "Date":"2019-12-03"
    }]

5 Answers 5

2

You can create a custom cleanup function and then use filter

Ex:

import datetime
import uuid

class CheckModel(object):

    def __init__(self,SerialNumber,UID, Guid = None,Date = None):
        self.SerialNumber = SerialNumber
        self.UID = UID
        self.Guid = str(uuid.uuid4()) if Guid is None else Guid
        self.Date = datetime.datetime.now().isoformat() if Date is None else Date

#Clean Up Function.             
def clean_data(data):
    if all(key in data for key in ("Guid", "SerialNumber", "UID", "Date")):
        try:
            datetime.datetime.strptime(data["Date"], "%Y-%m-%dT%H:%M:%S.%fZ")
            return True
        except:
            pass
    return False 


test = [{
        "Guid":"d0c035a7-0e01-4a37-8fe9-251fb5633fc9",
        "SerialNumber":"1716154A",
        "UID":"F13BDB3B",
        "Date":"2019-12-03T13:50:19.882Z"

    },
    {
        "Guid":"d0585-0e01-4a47-8fe9-251245f33fc9",
        "SerialNumber":"1716154A",
        "Date":"2019-12-03T13:50:19.882Z"
    },
    {
        "Guid":"12414a7-0e01-4a47-8fe9-251245f33fc9",
        "SerialNumber":"1716154A",
        "UID":"F13BDB3B",
        "Date":"2019-12-03"
    }]

model_data = [CheckModel(**data) for data in filter(clean_data, test)]
print(model_data)

Output:

[<__main__.CheckModel object at 0x0000000002F0AFD0>]
Sign up to request clarification or add additional context in comments.

Comments

0

As you already have an initializer for the CheckModel class you should be able to just pass the values from the dict to this function:

check_model = CheckModel(test[0]['SerialNumber'], test[0]['UID'], test[0]['Guid'], test[0]['Date'])

Comments

0

If you just want the first one, you can use **kwargs to unpack a dictionary as a mapping into your __init__

some_object = CheckModel(**test[0])

However, this will only work if all of the keys are available as arguments of the function. This will raise an exception if you try this with test[1], since the UID arg will be missing

Comments

0

Use **kwargs to pass the dictionary as an argument to the constructor, which will unpack the dictionary as a list of argument

In addition, I would suggest making UID=None since UID was missing in one of the dictionaries of the list. Below will parse all elements of list into the Class

import datetime as datetime

class CheckModel(object):

    #Made UID None since it is not present in one of the dictionaries
    def __init__(self,SerialNumber,UID=None, Guid = None,Date = None):
        self.SerialNumber = SerialNumber
        self.UID = UID
        self.Guid = str(uuid.uuid4()) if Guid is None else Guid
        self.Date = datetime.now().isoformat() if Date is None else Date

test = [{
        "Guid":"d0c035a7-0e01-4a37-8fe9-251fb5633fc9",
        "SerialNumber":"1716154A",
        "UID":"F13BDB3B",
        "Date":"2019-12-03T13:50:19.882Z"

    },
    {
        "Guid":"d0585-0e01-4a47-8fe9-251245f33fc9",
        "SerialNumber":"1716154A",
        "Date":"2019-12-03T13:50:19.882Z"
    },
    {
        "Guid":"12414a7-0e01-4a47-8fe9-251245f33fc9",
        "SerialNumber":"1716154A",
        "UID":"F13BDB3B",
        "Date":"2019-12-03"
    }]

models = []

for item in test:
    #Use **kwargs to pass dictionary as arguments to constructor
    models.append(CheckModel(**item))
print(models)

To just create the object of first item in the list, do

CheckModel(**test[0])

Comments

0

This should give you access to the first element of the list and then you can parse out the dictionary as necessary.

elem = check_model[0]

# Use the get() function on a dictionary to get the value of key without 
# breaking the code if the key doesn't exist
guid = elem.get('Guid')
serial_number = elem.get('SerialNumber')
uid = elem.get('UID')
date = elem.get('Date')

instance = CheckModel(serial_number, uid, Guid=guid, Date=date)

# Do something with it
instance.do_something()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.