Second attempt WAS: From Dict to Classes yes or no and how

Dave Angel davea at ieee.org
Tue Jun 22 09:18:12 EDT 2010



Jerry Rocteur wrote:
>> On Tue, Jun 22, 2010 at 9:32 PM, Jerry Rocteur <macosx at rocteur.cc> wrote:
>> If you were able to ask us perhaps a more specific question
>> and describe your problem a little more concisely perhaps
>> I (and we) might have a bit more to offer you.
>>     
>
> I have a dictionary:
>
> users[key] = {    'user'        : key,
>                   'secnum'      : secnum,
>                   'name'        : name
>              }
>
> Is it possible for me to code a class like this:
>
> class GRPUser(object):
>     def __init__(self, user, secnum, name, groups=None):
>         self.user          = user
>         self.secnum        = secnum
>         self.name          = name
>
> Which would allow me to iterate through and access specific records ?
>
> How do I iterate through and access an individual user record!
>
> Thanks in advance,"
>
> Jerry
>
>   
I believe you have a dictionary of dictionaries.  The outer level one is 
called users, and a key to that dictionary is a string containing a user 
name.

What you want to do is replace the inner dictionary with an instance of 
a custom class, and you'd like to know how.

First, I'd point out that it's already a class, called dict.  Using your 
own class can give some advantages, but you have to decide if you want 
or need them.

I don't see how having the data for one user as a class object will make 
any difference in how you find that object, or how you iterate through a 
dictionary or list of such objects.  But if it's what you want...

class  GRPUser(object):
    def __init__(self, mydict):
          self.user = mydict["user"]
          self.secnum = mydict["secnum"]
          self.name = mydict["name"]
          self.groups = None

Now to find a particular user, say
   currentuser = "Joe"

Just   use  users[currentuser]

To loop through all the users,
     for user in users:
           ...do something with user...

To change the groups attribute of a particular user,
     users[currentuser].groups =  ...newvalue...

DaveA




More information about the Python-list mailing list