473,573 Members | 2,922 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

list/tuple to dict...

Hi,

Is the following a reasonable generic approach for converting python
returned tuples/lists into dicts...? I'm not advocating library functions
also return dicts (I'd probably spend more time looking up the real
names... :) I'm just looking to make my code more readable and
self-documenting...
--------
class todict:
""" Converts a list/tuple to a dict: foo = todict(values,n ames) """
def __init__(self,v alues,names):
self.d = {}
for i,name in enumerate(names .split(",")):
self.d[name.strip()]=values[i]
def __setitem__(sel f, name, value):
self.d[name]=value
def __getitem__(sel f, name):
return self.d[name]

import os

# called this way, I can see what is returned in what order
uname = todict(os.uname (), "sysname, nodename,releas e,version, machine")

filename = "/etc/passwd"
osstat = todict(os.stat( "%s" % filename),
"mode,inode,dev ,nlink,uid,gid, size,atime,mtim e,ctime")
osstat['filename'] = filename

print "You're running %(sysname)s %(release)s on %(nodename)s" % uname
# mtime needs formatting...
print "File '%(filename)s' was last modified %(mtime)s" % osstat
---------
Returns:
You're running Linux 2.6.3-15mdk on gypsy.pfortin.c om
File '/etc/passwd' was last modified 1080568025

A number of values are set and not used; though I think it's a small
price to pay for making the results of lists/tuples more readable and
useful...

Over time, I'll probably build a list of functions I use and just
copy/paste the line(s) I need:

~/pytemplates:
osstat = todict(os.stat( "%s" % path),
"mode,inode,dev ,nlink,uid,gid, size,atime,mtim e,ctime")
uname = todict(os.uname (),
"sysname, nodename,releas e,version, machine")
etc...

The only part I still don't like is:
osstat['filename'] = filename

Is there a way to rewrite the class to allow for calls which take parms to
include the parms in the resulting dict..? I'm probably trying to get too
cute here though... :^)

The newbie who gets to read (maintain?) my code should have an easier
time; at least, that's my intent... Though Alex will probably consider
this boilerplating.. . I think .some. boilerplating is good... B-]

Other suggestions welcome :^)

Thanks,
Pierre

Jul 18 '05 #1
17 4269
Pierre Fortin wrote:
osstat = todict(os.stat( "%s" % path),
"mode,inode,dev ,nlink,uid,gid, size,atime,mtim e,ctime")
uname = todict(os.uname (),
"sysname, nodename,releas e,version, machine")


Use

dict(zip(["mode,inode,dev ,nlink,uid,gid, size,atime,mtim e,ctime"],
os.stat("%s" % path)))
--
Regards,

Diez B. Roggisch
Jul 18 '05 #2
[Pierre Fortin]
I'm just looking to make my code more readable and
self-documenting... . . . osstat = todict(os.stat( "%s" % path),
"mode,inode,dev ,nlink,uid,gid, size,atime,mtim e,ctime")

[Diez B. Roggisch] Use

dict(zip(["mode,inode,dev ,nlink,uid,gid, size,atime,mtim e,ctime"],
os.stat("%s" % path)))


Why build the dictionary at all. Use the named attributes provided by os.stat:

mode = os.stat(f).st_m ode

That should meet the original readability goals.
Raymond Hettinger
Jul 18 '05 #3
On Wed, 15 Sep 2004 22:58:26 GMT Raymond wrote:
[Pierre Fortin]
I'm just looking to make my code more readable and
self-documenting... . . . osstat = todict(os.stat( "%s" % path),
"mode,inode,dev ,nlink,uid,gid, size,atime,mtim e,ctim
e")

[Diez B. Roggisch]
Use

dict(zip(["mode,inode,dev ,nlink,uid,gid, size,atime,mtim e,ctime"],
os.stat("%s" % path)))


What does zip() have to do with this situation...?

Why build the dictionary at all. Use the named attributes provided by
os.stat:

mode = os.stat(f).st_m ode

That should meet the original readability goals.


That'll teach me to use examples that already have named attributes... :^)
I'm looking to do this generically -- ignore the few that do have named
attributes; there are plenty without that I'd like to address...

The goal is to use the dict in string mapping keys as indicated in my
original post.
Jul 18 '05 #4
Pierre Fortin wrote:
> dict(zip(["mode,inode,dev ,nlink,uid,gid, size,atime,mtim e,ctime"],
> os.stat("%s" % path)))
What does zip() have to do with this situation...?


It combines the items in the names list with the os.stat() result tuple to a
list of (name, value) pairs that are then used to initialize the
dictionary. For example:
name_value_pair s = zip(["name1", "name2", "nameN"], ["va11", "val2", "valN"]) name_value_pair s [('name1', 'va11'), ('name2', 'val2'), ('nameN', 'valN')] dict(name_value _pairs) {'nameN': 'valN', 'name2': 'val2', 'name1': 'va11'}

Why build the dictionary at all. Use the named attributes provided by
os.stat:

mode = os.stat(f).st_m ode

That should meet the original readability goals.


That'll teach me to use examples that already have named attributes... :^)
I'm looking to do this generically -- ignore the few that do have named
attributes; there are plenty without that I'd like to address...

The goal is to use the dict in string mapping keys as indicated in my
original post.


You can still do that while relying on the existing names:
class ObjectAsDictAda pter: .... def __init__(self, obj):
.... self.obj = obj
.... def __getitem__(sel f, key):
.... return getattr(self.ob j, key)
.... import os
st = os.stat("tmp.py ")
"%(st_mtime )s %(st_size)s" % ObjectAsDictAda pter(st) '1095318348 2'


You can easily add an analogous

def __setitem__(sel f, key, value):
setattr(self.ob j, key, value)

but it won't work in the above example as the stat tuple is immutable.
If you need other attributes (like filename in your original post) you can
solve that with Raymond Hettinger's Chainmap

http://aspn.activestate.com/ASPN/Coo.../Recipe/305268

#untested
"%(filename )s %(st_size)s" % Chainmap(Object AsDictAdapter(s t),
dict(filename=f ilename))

Peter
Jul 18 '05 #5
Pierre Fortin <pf*****@pforti n.com> wrote:
...
class todict:
""" Converts a list/tuple to a dict: foo = todict(values,n ames) """
def __init__(self,v alues,names):
self.d = {}
for i,name in enumerate(names .split(",")):
self.d[name.strip()]=values[i]
def __setitem__(sel f, name, value):
self.d[name]=value
def __getitem__(sel f, name):
return self.d[name]
You can implement this exact functionality (not worth it for os.stat, of
course, which already does return a pseudotuple with named items) in a
probably better way...:

import itertools

...

def __init__(self, values, names):
self.d = dict(itertools. izip(
map(str.strip, names.split(',' )),
values))

However, as recently discussed on this group, this is going to put a
dictionary in EVERY instance of 'todict' dealing with the same sequence
of names. Normally when you deal with tuples whose items have certain
names, you will deal with a lot of such tuples with the same item names.
It seems better to me to make a TYPE which deals with the name-to-index
mapping, then instantiate that type as needed with tuples of values.
Over time, I'll probably build a list of functions I use and just
copy/paste the line(s) I need:
Copy and paste is a BAD way to reuse software. Very, very bad. Anybody
with the least experience maintaining big programs will confirm.
Is there a way to rewrite the class to allow for calls which take parms to
include the parms in the resulting dict..? I'm probably trying to get too
cute here though... :^)
You can easily add keyword args to the __init__:

def __init__(self, values, names, **kw):
self.d = dict(itertools. izip(
map(str.strip, names.split(',' )),
values), **kw)

This way you can set extra parameters as you instantiate todict.

The newbie who gets to read (maintain?) my code should have an easier
time; at least, that's my intent... Though Alex will probably consider
this boilerplating.. . I think .some. boilerplating is good... B-]

Other suggestions welcome :^)


My suggestion is to rethink your thesis that some boilerplate is good.
The first time in your life you must make a change and hunt down every
place you have c&p'd your boilerplate -- forget some place and get
anomalies -- etc, etc -- you'll see why. But why _must_ some people
make themselves the mistakes many previous generations have already
made, when members of those older generations keep alerting them to said
mistakes? Can't you be original and make YOUR OWN brand-new mistakes?!

Ah well. Making a specific type for each given sequence of item names
is clearer, conceptually preferable, faster, not wasteful of memory, and
lacks any countervailing counterindicati on -- yet you like boilerplate,
you like copy and paste, and _want_ all of the overheads you pay to get
them. OK, I'm not going to repeat once again the details on how to make
a type -- I must have posted them three times over the last 10 days or
so, enough is enough. Just one last attempt at motivation in case you
are at all superstitious.. .: should anybody else ever find themselves
maintaining your sw and find out that you DELIBERATELY inflicted this
chore on them because of your preference for boilerplate and c&p over
cleaner and lighter-weight approaches, don't be surprised if your tea
kettles never boil, your cat scratches you, and you find yourself having
to get new tires often because you keep hitting nails and shards of
glass on the street... it's just the MILDEST kind of curses those poor
software maintainers are streaming towards you constantly, starting to
work on the astral plane... ((ok, ok, I don't necessarily _believe_
this, but hey, if anybody does and I can thereby motivate them to write
better sw than they otherwise would, why, I think that's justification
enough for this little white, ahem, working hypothesis I'm
presenting!-))
Alex
Jul 18 '05 #6
Pierre Fortin wrote:
On Wed, 15 Sep 2004 22:58:26 GMT Raymond wrote:
[Pierre Fortin]
> > I'm just looking to make my code more readable and
> > self-documenting...

. . .
> > osstat = todict(os.stat( "%s" % path),
> > "mode,inode,dev ,nlink,uid,gid, size,atime,mtim e,ctim
> > e")


[Diez B. Roggisch]
> Use
>
> dict(zip(["mode,inode,dev ,nlink,uid,gid, size,atime,mtim e,ctime"],
> os.stat("%s" % path)))


What does zip() have to do with this situation...?


Uhm - its needed?

It creates a list of pairs from the two argument lists, and dict() takes a
list of pairs of (key, value) to form a dictionary.

--
Regards,

Diez B. Roggisch
Jul 18 '05 #7
Alex Martelli wrote:
Pierre Fortin <pf*****@pforti n.com> wrote:
... [...]
Over time, I'll probably build a list of functions I use and just
copy/paste the line(s) I need:

Copy and paste is a BAD way to reuse software. Very, very bad. Anybody
with the least experience maintaining big programs will confirm.

Yup. Make a mistake before c&p and you then have two places to fix it
rather than one. Or three, or four, or an unknown number ...
Is there a way to rewrite the class to allow for calls which take parms to
include the parms in the resulting dict..? I'm probably trying to get too
cute here though... :^)

You can easily add keyword args to the __init__:

def __init__(self, values, names, **kw):
self.d = dict(itertools. izip(
map(str.strip, names.split(',' )),
values), **kw)

This way you can set extra parameters as you instantiate todict.
The newbie who gets to read (maintain?) my code should have an easier
time; at least, that's my intent... Though Alex will probably consider
this boilerplating.. . I think .some. boilerplating is good... B-]

Other suggestions welcome :^)

My suggestion is to rethink your thesis that some boilerplate is good.
The first time in your life you must make a change and hunt down every
place you have c&p'd your boilerplate -- forget some place and get
anomalies -- etc, etc -- you'll see why. But why _must_ some people
make themselves the mistakes many previous generations have already
made, when members of those older generations keep alerting them to said
mistakes? Can't you be original and make YOUR OWN brand-new mistakes?!

One of the nicest things about c.l.py is its ability to soak up endless
repetitions of the same enquiries from newcomers and remain (almost)
unfailingly polite. I sense you are holding sclerotic tendencies in
check with the utmost self-control here - well done! Humor, that's the
trick.
Ah well. Making a specific type for each given sequence of item names
is clearer, conceptually preferable, faster, not wasteful of memory, and
lacks any countervailing counterindicati on -- yet you like boilerplate,
you like copy and paste, and _want_ all of the overheads you pay to get
them.
More accurately, probably hasn't yet written enough code to appreciate
the disadvantages of cut-and-paste methods. And I hope, now clued-up b y
a master, likely to eschew the vile habit forthwith.
OK, I'm not going to repeat once again the details on how to make
a type -- I must have posted them three times over the last 10 days or
so, enough is enough. Just one last attempt at motivation in case you
are at all superstitious.. .: should anybody else ever find themselves
maintaining your sw and find out that you DELIBERATELY inflicted this
chore on them because of your preference for boilerplate and c&p over
cleaner and lighter-weight approaches, don't be surprised if your tea
kettles never boil, your cat scratches you, and you find yourself having
to get new tires often because you keep hitting nails and shards of
glass on the street... it's just the MILDEST kind of curses those poor
software maintainers are streaming towards you constantly, starting to
work on the astral plane... ((ok, ok, I don't necessarily _believe_
this, but hey, if anybody does and I can thereby motivate them to write
better sw than they otherwise would, why, I think that's justification
enough for this little white, ahem, working hypothesis I'm
presenting!-))

If only there were some way we could avoid having to repeat good advice
so often (to avoid cutting and pasting it into so many c.l.py answers,
for example).

Don't forget to take your blood-pressure medication :-)

just-heard-the-kettle-boiling-ly y'rs - steve
Jul 18 '05 #8
al*****@yahoo.c om (Alex Martelli) wrote:
Copy and paste is a BAD way to reuse software. Very, very bad. Anybody
with the least experience maintaining big programs will confirm.


Absolutely agree.

A while ago, I was working on a piece of code written by somebody who
didn't believe in this. I found a bug and fixed it. Sometime later, we
realized the fix was wrong and I went back to make an additional change.

I was surprised when the file I was looking at appeared to be the
original code. Where had my first change gone? We spent an afternoon
looking through CVS logs, getting ourselves more and more convinced that
CVS had somehow messed up.

It turns out, the fix I made was in a huge function (100's of lines)
which somebody had cut-and-pasted to make three versions which did
almost identical things. And then they gave the functions almost
identical names, along the lines of:

sendMessageToSe rverWithAlertCo ndition ()
sendMessageToSe rverWithErrorCo ndition ()
sendMessageToSe rverWithOtherCo ndition ()

So, yeah, Alex is right. Don't do that.
Jul 18 '05 #9
Steve Holden <sh*****@holden web.com> wrote:
...
Don't forget to take your blood-pressure medication :-)

just-heard-the-kettle-boiling-ly y'rs - steve


Heh -- thanks Steve, but you misinterpreted, that was just Anna making
tea;-). I'm just going to take some Maalox... the pressure is fine!-)
Alex
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2083
by: Ishwar Rattan | last post by:
I am a little confused about a list and a tuple. Both can have dissimilar data-type elements, can be returned by functions. The only difference that I see is that list is mutable and tuple is not (of course list have .append() etc.) What is a possible scenario where one is preferred over the other? -ishwar
7
1485
by: Ben | last post by:
Hi In a list I have a number of soccer players. Each player has a different rating for attacking, defending, midfield fitness and goalkeeping. I have devised a while loop that goes through this list to find the best player at defending, attacking, midfield and goalkeeping. However there is more than one defender per team so I therefore...
16
23001
by: flyaflya | last post by:
a = "(1,2,3)" I want convert a to tuple:(1,2,3),but tuple(a) return ('(', '1', ',', '2', ',', '3', ')') not (1,2,3)
7
4429
by: Shafik | last post by:
Hello folks, I am an experienced programmer, but very new to python (2 days). I wanted to ask: what exactly is the difference between a tuple and a list? I'm sure there are some, but I can't seem to find a situation where I can use one but not the other. Thanks in advance, --Shafik
25
4082
by: beginner | last post by:
Hi, I am wondering how do I 'flatten' a list or a tuple? For example, I'd like to transform or ] to . Another question is how do I pass a tuple or list of all the aurgements of a function to the function. For example, I have all the arguments of a function in a tuple a=(1,2,3). Then I want to pass each item in the tuple to a function f...
16
28710
by: Davy | last post by:
Hi all, We know that list cannot be used as key of dictionary. So, how to work around it? For example, there is random list like l=. Any suggestions are welcome! Best regards,
3
1739
by: bruce | last post by:
hi guys/gals... got a basic question that i can't get my hands around. i'm trying to programatically create/use a list/tuple (or whatever the right phrase in pyton is!!) basically, something like: foo = foo.append('cat')
0
1016
by: bruce | last post by:
Hi Fredrik... so, this still doesn't get me an array called 'cat', or 'dog' or do i somehow use stuff to add/extract the vals...??? thanks -----Original Message-----
3
1602
by: flit | last post by:
Hello All, I will appreciate the help from the more skillfull pythonistas.. I have a small app that generates a sequence like 00341 01741 03254
0
7780
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7694
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8202
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7787
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8065
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5593
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5291
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
2213
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1303
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.