Advertisement
here2share

# dict2class.py

Jul 3rd, 2019
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.70 KB | None | 0 0
  1. # dict2class.py -- designed mainly for json usage
  2.  
  3. import types
  4.  
  5. def dict2class(d):
  6.     """
  7.         Return a class that has same attributes/values and
  8.         dictionaries key/value
  9.     """
  10.  
  11.     # see if it is indeed a dictionary
  12.     if type(d) != types.DictType:
  13.         return None
  14.  
  15.     # define a dummy class
  16.     class Dummy: 0
  17.        
  18.     c = Dummy
  19.     # each key need to be given as a string variable
  20.     for e in d.keys():
  21.         c.__dict__[e] = d[e]
  22.     return c
  23.  
  24. employees = {}
  25.  
  26. employees['Tom Katt'] = dict2class( {   'age': 17,
  27.                                         'title': 'Cashier' } )
  28. employees['Barb Wyre'] = dict2class( {  'age': 32,
  29.                                         'title': 'Manager' } )
  30.  
  31. for id in employees:
  32.     print id
  33.     print employees[id].title
  34.     print employees[id].age
  35.     print
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement