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

2010-06-24 Thread Colin J. Williams

On 22-Jun-10 08:03 AM, Jerry Rocteur wrote:

On Tue, Jun 22, 2010 at 9:32 PM, Jerry Rocteur  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


Jerry,

You are pushing your luck with so many repetitions of your posting.

First, you probably don't need the line 'user':key.  items() delivers 
this for you.


If every record has the same structure, you could work with the tuple 
(secnum, name).


It's not clear what the role of the class instance will be.

Colin W.

--
http://mail.python.org/mailman/listinfo/python-list


Re: From Dict to Classes yes or no and how

2010-06-22 Thread Andreas Waldenburger
On Tue, 22 Jun 2010 13:56:43 +0200 (CEST) "Jerry Rocteur"
 wrote:

> As part of learning Python, I'm also learning OOP! That is why I want
> to know if this is doable using classes.

Everything[1] is doable using classes. The question is: Do you *need* to
do it with classes? If your problem is best described as "mappings from
keys to values", then you have already implemented a fine solution
with dicts.

Think of "objects" as "things with behavior". Basically, if you have
many top-level data items (such as dicts, lists, whatever), and many
functions operating on these, grouping these data items with the
appropriate functions within classes might clean up your code
conceptually (It might! I didn't say it will!).

If you can categorize these data/function groups into a hierarchical
structure of ever more specialized functionality, then classes and
inheritance are pretty much your friends by default.

So the takeaway is this: Will you (and possibly others) be able to
understand my code better by organizing it in this-or-that structure?
If so, use this-or-that structure, if not, then don't.


And to even more evade answering your specific question: If you have
the time, go and rewrite your code with classes. That'll teach you more
than theorizing about *maybe doing* it here.

/W

[1] For sufficiently small values of "everything".

-- 
INVALID? DE!

-- 
http://mail.python.org/mailman/listinfo/python-list


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

2010-06-22 Thread Dave Angel



Jerry Rocteur wrote:

On Tue, Jun 22, 2010 at 9:32 PM, Jerry Rocteur  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

--
http://mail.python.org/mailman/listinfo/python-list


Re: From Dict to Classes yes or no and how

2010-06-22 Thread Jean-Michel Pichavant

Jerry Rocteur wrote:

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 06/22/2010 01:32 PM, Jerry Rocteur wrote:


My input is NOT CSV, I used this format to try and make the question shorter. 
Although I could create a CSV file,
I'd
like to learn how to code a class to work the way I described in the question.
  

Sorry for misunderstanding. Can you maybe give one example that's not
CSV? Both your demonstrated files actually are CSV like. Can you be more
specific on what actually changes constantly. (Fields given in the
files, or the users in the files, or...)
Can you tell us, why you want to use classes if the dict approach works
great?



As part of learning Python, I'm also learning OOP! That is why I want to know 
if this is doable using classes.

The input is not important, I end up with the dictionary as described in the 
question and as I asked in the question,
I'd like to access the dictionary as a class and I don't know how or if it is 
possible.


Jerry

  
Dictionary is already a class in python, everything is an object 
actually (even class are objects).


A python OOP approach to your problem would be to subclass the builtin 
'dict' class and override / add the methods.


Here is an example how you can for your User dictionary to accept only 
some types of values.


class User(object):
   def __init__(self, user, secnum, name):
   self.user = user
   self.secnum = secnum
   self.name = name

   def __str__(self):
   return "%(name)s <%(user)s> -- secnum :%(secnum)d" % self.__dict__

   def __repr__(self):
   return self.__str__()

class Users(dict):
   def __init__(self):
   dict.__init__(self) # call the baseclass constructor

   def __setitem__(self, user, value):
   if isinstance(value, User):
   dict.__setitem__(self, user, value)
   else:
   try:
   dict.__setitem__(self, user, User(user, value[0], value[1]))
   except KeyError:
   raise ValueError ("Invalid user format, it shoudl be 
either a User object or a tuple (secnum, name)")
  
users = Users()


users['jro'] = (1325,'john') # the overriden __setitem__ method wil 
ltake care of creating the User object for you.

users['dma'] = User('dma', 654968, 'dominic')

for user in users:
   print users[user]

# Users objects inherit all dict method, values() for instance
for user in users.values():
   print user



For more information: http://docs.python.org/reference/datamodel.html
Read carefully the 3.4.6  section (Emulating container type)


JM
--
http://mail.python.org/mailman/listinfo/python-list


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

2010-06-22 Thread Andre Alexander Bell
On 06/22/2010 02:03 PM, Jerry Rocteur wrote:
>> On Tue, Jun 22, 2010 at 9:32 PM, Jerry Rocteur  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
> 

So far your class is perfectly fine, representing the data in form of a
class having an object for each individual user.

> Which would allow me to iterate through and access specific records ?

That actually is not part of the class nor should it even be part of the
class. You would probably end up with something comparable to your
initial dict to 'lookup' the objects.

users = {}
users['jdoe'] = GRPUser('jdoe', ...)
...

This dict is something like an index from user id to user objects. You
may then setup an index for the secnum (if unique) the same way:

secnums = {}
secnums[12345] = users['jdoe']
...

Note, that I did set the identical object in the other index dict.
Modifying users['jdoe'] would modify secnums[12345]!
This is what you actually want from an index...

> How do I iterate through and access an individual user record!

You iterate over the index...


Andre
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2010-06-22 Thread James Mills
On Tue, Jun 22, 2010 at 10:03 PM, Jerry Rocteur  wrote:
>> On Tue, Jun 22, 2010 at 9:32 PM, Jerry Rocteur  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,

I'm not sure what's wrong with your email client but I already
answered this for you.

To access an individual record given that you have a dict
called "users" that holds a mapping of username to user record/object
simply select an individual record by it's key (username). eg:

>>> users["Bob Jane"]

cheers
James
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2010-06-22 Thread Jerry Rocteur
> On Tue, Jun 22, 2010 at 9:32 PM, Jerry Rocteur  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

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: From Dict to Classes yes or no and how

2010-06-22 Thread Bruno Desthuilliers

Jerry Rocteur a écrit :
(snip)

As part of learning Python, I'm also learning OOP! That is why I want to know 
if this is doable using classes.

>

The input is not important, I end up with the dictionary as described in the 
question and as I asked in the question,
I'd like to access the dictionary as a class


I assume you mean "as an object" (or "as an instance of a class" - which 
is exactly the same thing). If you don't understand what this means, 
then you should first learn the difference between a class and an 
instance !-)



and I don't know how or if it is possible.


Well, Python being 100% object, your dict is already an object (an 
instance of the builtin 'dict' class).



--
http://mail.python.org/mailman/listinfo/python-list


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

2010-06-22 Thread James Mills
On Tue, Jun 22, 2010 at 10:03 PM, Jerry Rocteur  wrote:
> How do I iterate through and access an individual user record!

A much better question! :)

You are in fact already demonstrating that you know full
well how to access a specific user record - by accessing
a parent dictionary holding a mapping of user -> user record.

You select a user record by key.

>>> users["Bob Jane"]

Your example of a user record if perfectly fine to me.

If you wanted to iterate over all user records:

>>> for k, v in users.items():
...   # some code here

cheers
James

-- 
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: From Dict to Classes yes or no and how

2010-06-22 Thread James Mills
On Tue, Jun 22, 2010 at 9:56 PM, Jerry Rocteur  wrote:
> As part of learning Python, I'm also learning OOP! That is why I want to know 
> if this is doable using classes.
>
> The input is not important, I end up with the dictionary as described in the 
> question and as I asked in the question,
> I'd like to access the dictionary as a class and I don't know how or if it is 
> possible.

I suggest you start playing around with python classes and objects.

It's entirely possible you can create your own class that
represents your data and store this in some fashion.

You could also subclass (you'll learn about this) the dict class
creating your own customized dict (if you will).

The former approach may be better suited however instead of
diving into things you may not yet come to fully understand
until you really learn the inner workings of python :)

cheers
James

-- 
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2010-06-22 Thread Jerry Rocteur
> On Tue, Jun 22, 2010 at 9:32 PM, Jerry Rocteur  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

-- 
http://mail.python.org/mailman/listinfo/python-list


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

2010-06-22 Thread Jerry Rocteur
> On Tue, Jun 22, 2010 at 9:32 PM, Jerry Rocteur  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

-- 
http://mail.python.org/mailman/listinfo/python-list


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

2010-06-22 Thread Jerry Rocteur
> On Tue, Jun 22, 2010 at 9:32 PM, Jerry Rocteur  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

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: From Dict to Classes yes or no and how

2010-06-22 Thread Jerry Rocteur
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> On 06/22/2010 01:32 PM, Jerry Rocteur wrote:
>> My input is NOT CSV, I used this format to try and make the question 
>> shorter. Although I could create a CSV file,
>> I'd
>> like to learn how to code a class to work the way I described in the 
>> question.
>
> Sorry for misunderstanding. Can you maybe give one example that's not
> CSV? Both your demonstrated files actually are CSV like. Can you be more
> specific on what actually changes constantly. (Fields given in the
> files, or the users in the files, or...)
> Can you tell us, why you want to use classes if the dict approach works
> great?

As part of learning Python, I'm also learning OOP! That is why I want to know 
if this is doable using classes.

The input is not important, I end up with the dictionary as described in the 
question and as I asked in the question,
I'd like to access the dictionary as a class and I don't know how or if it is 
possible.


Jerry

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: From Dict to Classes yes or no and how

2010-06-22 Thread James Mills
On Tue, Jun 22, 2010 at 9:32 PM, Jerry Rocteur  wrote:
> My input is NOT CSV, I used this format to try and make the question shorter. 
> Although I could create a CSV file, I'd
> like to learn how to code a class to work the way I described in the question.

Your input certainly looks CSV-ish to me (us).

Even I didn't bother reading your email in full (sorry but it was too long!).

If you're not familiar with using classes and objects in python
perhaps you should read through relevant documentation
and/or tutorials on the subject.

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.

cheers
James

-- 
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: From Dict to Classes yes or no and how

2010-06-22 Thread Andre Alexander Bell
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 06/22/2010 01:32 PM, Jerry Rocteur wrote:
> My input is NOT CSV, I used this format to try and make the question shorter. 
> Although I could create a CSV file, I'd
> like to learn how to code a class to work the way I described in the question.

Sorry for misunderstanding. Can you maybe give one example that's not
CSV? Both your demonstrated files actually are CSV like. Can you be more
specific on what actually changes constantly. (Fields given in the
files, or the users in the files, or...)
Can you tell us, why you want to use classes if the dict approach works
great?

Regards


Andre

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.10 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkwgo10ACgkQnuHMhboRh6QpCACePUckiiafgAM/h65/THfFQNgZ
RmwAn35of1VvLTNALA/pTme5gKA8g683
=oYjv
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: From Dict to Classes yes or no and how

2010-06-22 Thread Jerry Rocteur
> On 06/22/2010 12:05 PM, Jerry Rocteur wrote:
>> Sorry for the long mail but I've been searching the web for days for how to 
>> do this.. I see that possibilities using
>> shelve or pickle but I don't want to do this (The source of the data changes 
>> constantly)
>
> You might be interested in the csv module
>
> http://docs.python.org/library/csv.html
>
> Regards
>
>
> Andre

My input is NOT CSV, I used this format to try and make the question shorter. 
Although I could create a CSV file, I'd
like to learn how to code a class to work the way I described in the question.

Jerry

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: From Dict to Classes yes or no and how

2010-06-22 Thread Andre Alexander Bell
On 06/22/2010 12:05 PM, Jerry Rocteur wrote:
> Sorry for the long mail but I've been searching the web for days for how to 
> do this.. I see that possibilities using
> shelve or pickle but I don't want to do this (The source of the data changes 
> constantly)

You might be interested in the csv module

http://docs.python.org/library/csv.html

Regards


Andre

-- 
http://mail.python.org/mailman/listinfo/python-list


From Dict to Classes yes or no and how

2010-06-22 Thread Jerry Rocteur
Hi,

Sorry for the long mail but I've been searching the web for days for how to do 
this.. I see that possibilities using
shelve or pickle but I don't want to do this (The source of the data changes 
constantly)

I'm learning Python and very much a beginner with Classes.

I have data like this: (highly simplified)

user is unique!

File1
user;secnum;name
jro;012345;John Rogers
dbt;012346;Debbie Row
dri;012347;Daniel Deridder
etc.

File2
group,user
ace1,jro
ace2,jro
ace1,dri
ace3,dbt
ace3.dbt
ace3.jro
etc.

At the moment I read, split into a dict like this:

Read through File1
users = {}
key   = splits[0]
users[key] = {'user': key,
  'secnum'  : splits[1],
  'name': splits[2]
 }

Read through File2
user= splits[0]
group   = splits[1]
users[user]['groups'].append(group)

This works great ..

But shouldn't I do this using classes instead ?

So I try

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

So how do I load the Class, iterate through it and call up individual users ?

I've tried all sorts of things u = GRPUser(user, split[1], split[2]) whilst 
reading File1, I get no errors but I have
no idea how to read in file2 and worse of all, no idea how to iterate through 
or call up individual items from the
class, for example:

print users['jro']['name'], users['jro']['secnum'], users['jro']['groups']

or

for keys in users:
print users[keys]['name']
for group in users[keys]['groups']:
print group

etc.

Thanks in advance,

jerry

-- 
http://mail.python.org/mailman/listinfo/python-list