1

I have this dictionary:

{"id":3,"name":"MySQL","description":"MySQL Database Server - Fedora 21 - medium","image":"","flavor":""}

And I have this object:

class Record():
    id = None
    name = None
    description = None
    image = None
    flavor = None

How can I assign values from the dictionary to their corresponding class fields?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Eugene Goldberg
  • 14,286
  • 20
  • 94
  • 167

7 Answers7

3

Take a dict object as the parameter of init function:

class Record(object):
  def __init__(self,record_dict):
    try:
      self.id = record_dict['id']
      self.name = record_dict['name']
      self.description = record_dict['description']
      self.image = record_dict['image']
      self.flavor = record_dict['flavor']
    except KeyError:
      print 'KeyError'

  def get_name(self):
    return self.name

adict = {"id":3,"name":"MySQL","description":"MySQL Database Server - Fedora 21 - medium","image":"","flavor":""}

one_obj = Record(adict)

print one_obj
print one_obj.get_name()

output:

<__main__.Record object at 0x022E4C90>
MySQL

works for me...

lqhcpsgbl
  • 3,694
  • 3
  • 21
  • 30
2

You probably want something like this:

class Record:
def __init__(self, myDict):
    self.id = myDict[“id”]
    self.name = myDict[“name”]
    self.description = myDict[“description”]
    self.image = myDict[“image”]
    self.flavor = myDict[“flavor”]

And call it:

rec = Record(myDict)

See here to understand the difference between class and instance variables.

Long story short, class variables have a single value for every instance of the class while instance variables values are unique to each instance.

A class variable is defined like this:

class myClass:
    Classvar =  ‘something’

An instance variable is defined like this:

class myClass:
    def __init__():
        Self.instanceVar = ‘something else’ 
JasonPap
  • 98
  • 6
2

This has already been answered here: Convert Python dict to object?

My favorite method is this one: x.__dict__.update(d)

Community
  • 1
  • 1
Brent Washburne
  • 12,904
  • 4
  • 60
  • 82
1

You can assign them as follows, assuming your dictionary name is input

id = input['id']
name = input['name']
description = input['description']
image = input['image']
flavor = input['flavor']
Amit
  • 19,780
  • 6
  • 46
  • 54
1

Try this method in which you grab the attributes of the object:

r = Record()
attributes = [i for i in dir(r) if not i.startswith('_')]

Basically, there are a bunch of background attributes that contain a bunch of underscores. The dir method gets all the attributes and we create a list of the ones that we want. At this point:

# attributes = ['count', 'description', 'flavor', 'id', 'image', 'index', 'name']

So now we use __setattr__ to set the attributes we just grabbed according to the my_dict

for i in attributes:
    r.__setattr__(i, my_dict[i])

See the code run online here.

Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
0

When you create the Record, pass in the dictionary. Then map the key to the value.

jnd
  • 754
  • 9
  • 20
0

Another simple method, see the code here

r = Record()

for k, v in my_dict.items():
    exec('r.' + k + '="' + str(v) + '"')
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70