problem of converting a list to dict

L

Louis.Soninhu

Hi pals

I have a list like this

mylist=['','tom=boss','mike=manager','paul=employee','meaningless']

I'd like to remove the first and the last item as they are irrevalent,
and convert it to the dict:
{'tom':'boss','mike':'manager','paul':'employee'}

I tried this but it didn't work:

mydict={}
for i in mylist[1:-1]:
a=i.split('=') # this will disect each item of mylist into a 2-item
list
mydict[a[0]]=a[1]

and I got this:
File "srch", line 19, in <module>
grab("a/tags1")
File "srch", line 15, in grab
mydict[mylist[0]]=mylist[1]
IndexError: list index out of range

Anyone could shed me a light on this?

thanks
 
F

Fredrik Lundh

I have a list like this

mylist=['','tom=boss','mike=manager','paul=employee','meaningless']

I'd like to remove the first and the last item as they are irrevalent,
and convert it to the dict:
{'tom':'boss','mike':'manager','paul':'employee'}

I tried this but it didn't work:

mydict={}
for i in mylist[1:-1]:
a=i.split('=')
mydict[a[0]]=a[1]

and I got this:
File "srch", line 19, in <module>
grab("a/tags1")
File "srch", line 15, in grab
mydict[mylist[0]]=mylist[1]
IndexError: list index out of range

Anyone could shed me a light on this?

works for me, with the mylist example you provided.

to see what's going on on your machine, try printing "a" after the
split, but before you use it to populate the dictionary.

</F>
 
M

Marc 'BlackJack' Rintsch

Hi pals

I have a list like this

mylist=['','tom=boss','mike=manager','paul=employee','meaningless']

I'd like to remove the first and the last item as they are irrevalent,
and convert it to the dict:
{'tom':'boss','mike':'manager','paul':'employee'}

I tried this but it didn't work:

mydict={}
for i in mylist[1:-1]:
a=i.split('=') # this will disect each item of mylist into a 2-item
list
mydict[a[0]]=a[1]

and I got this:
File "srch", line 19, in <module>
grab("a/tags1")
File "srch", line 15, in grab
mydict[mylist[0]]=mylist[1]
IndexError: list index out of range

Anyone could shed me a light on this?

The real list you used had at least one string without a '=' in it. The
list given above doesn't raise that exception:

In [102]: mylist=['','tom=boss','mike=manager','paul=employee','meaningless']

In [103]: mydict={}

In [104]: for i in mylist[1:-1]:
.....: a=i.split('=')
.....: mydict[a[0]]=a[1]
.....:

In [105]: mydict
Out[105]: {'mike': 'manager', 'paul': 'employee', 'tom': 'boss'}

Ciao,
Marc 'BlackJack' Rintsch
 
L

Louis.Soninhu

that's very strange...

the list I give here is almost same as the real list, except for the
length.

Thanks Marc, I'll go check what's wrong elsewhere
 
L

Louis.Soninhu

I have a list like this
mylist=['','tom=boss','mike=manager','paul=employee','meaningless']

I'd like to remove the first and the last item as they are irrevalent,
and convert it to the dict:
{'tom':'boss','mike':'manager','paul':'employee'}
I tried this but it didn't work:
mydict={}
for i in mylist[1:-1]:
   a=i.split('=')
   mydict[a[0]]=a[1]
and I got this:
  File "srch", line 19, in <module>
    grab("a/tags1")
  File "srch", line 15, in grab
    mydict[mylist[0]]=mylist[1]
IndexError: list index out of range
Anyone could shed me a light on this?

works for me, with the mylist example you provided.

to see what's going on on your machine, try printing "a" after the
split, but before you use it to populate the dictionary.

</F>- Hide quoted text -

- Show quoted text -

'print a' works
 
J

John Machin

Hi pals

I have a list like this

mylist=['','tom=boss','mike=manager','paul=employee','meaningless']

I'd like to remove the first and the last item as they are irrevalent,
and convert it to the dict:
{'tom':'boss','mike':'manager','paul':'employee'}

I tried this but it didn't work:

mydict={}
for i in mylist[1:-1]:
a=i.split('=') # this will disect each item of mylist into a 2-item

No it doesn't; it dissects i into a 2-item list if i is a string
containing exactly one '='.

DON'T rely on "knowing" that the first and last entries are the only
irrelevant ones. Do some checking. Conditions to check for:
(1) len(a) == 2
(2) a[0] is empty or not what you expect (a person's name)
(3) a[1] is empty or not what you expect (a job title)
(consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = '
boss')
(4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...]
 
L

Louis.Soninhu

oops, it seems there are other 'meaningless' item, which actually
caused the problem

Thanks for helps
 
J

John Machin

-----Original Message-----
From: [email protected] [mailto:python-
[email protected]] On Behalf Of Fredrik Lundh
Sent: Wednesday, January 09, 2008 2:39 PM
To: (e-mail address removed)
Subject: Re: problem of converting a list to dict
(e-mail address removed) wrote:
so what does it tell you?

A bigger hint:
a=i.split('=')
print "'%s' splits into " % (i), a

consider:
(1) using %r instead of '%s'
(2) omitting the redundant space after 'into'
(3) losing the redundant () around i

assert len(a) == 2
mydict[a[0]]=a[1]
 
T

Tim Chase

mylist=['','tom=boss','mike=manager','paul=employee','meaningless']
I'd like to remove the first and the last item as they are irrevalent,
and convert it to the dict:
{'tom':'boss','mike':'manager','paul':'employee'}

I tried this but it didn't work:

mydict={}
for i in mylist[1:-1]:
a=i.split('=') # this will disect each item of mylist into a 2-item
list
mydict[a[0]]=a[1]

and I got this:
File "srch", line 19, in <module>
grab("a/tags1")
File "srch", line 15, in grab
mydict[mylist[0]]=mylist[1]
IndexError: list index out of range

This can be rewritten a little more safely like

mydict = dict(pair.split('=',1)
for pair in mylist
if '=' in pair)

Some of John Machin's caveats still apply:
(2) a[0] is empty or not what you expect (a person's name)
(3) a[1] is empty or not what you expect (a job title)
(consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = '
boss')
(4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...]

to which I'd add

(5) what happens if you have more than one equals-sign in your
item? ("bob=robert=manager" or "bob=manager=big-cheese")


#2 and #3 can be ameliorated a bit by

import string
mydict = dict(
map(string.strip,pair.split('=',1))
for pair in mylist
if '=' in pair)

which at least whacks whitespace off either end of your keys and
values. #4 and #5 require a clearer definition of the problem.

-tkc
 
J

John Machin

mylist=['','tom=boss','mike=manager','paul=employee','meaningless']
I'd like to remove the first and the last item as they are irrevalent,
and convert it to the dict:
{'tom':'boss','mike':'manager','paul':'employee'}
I tried this but it didn't work:
mydict={}
for i in mylist[1:-1]:
a=i.split('=') # this will disect each item of mylist into a 2-item
list
mydict[a[0]]=a[1]
and I got this:
File "srch", line 19, in <module>
grab("a/tags1")
File "srch", line 15, in grab
mydict[mylist[0]]=mylist[1]
IndexError: list index out of range

This can be rewritten a little more safely like

mydict = dict(pair.split('=',1)
for pair in mylist
if '=' in pair)

Some of John Machin's caveats still apply:
(2) a[0] is empty or not what you expect (a person's name)
(3) a[1] is empty or not what you expect (a job title)
(consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = '
boss')
(4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...]

to which I'd add

(5) what happens if you have more than one equals-sign in your
item? ("bob=robert=manager" or "bob=manager=big-cheese")

or "bob==manager"

ummm ... isn't more than one equals-sign covered by check #1: len(a)
== 2
?
 
B

bsneddon

mylist=['','tom=boss','mike=manager','paul=employee','meaningless']
I'd like to remove the first and the last item as they are irrevalent,
and convert it to the dict:
{'tom':'boss','mike':'manager','paul':'employee'}
I tried this but it didn't work:
mydict={}
for i in mylist[1:-1]:
a=i.split('=') # this will disect each item of mylist into a 2-item
list
mydict[a[0]]=a[1]
and I got this:
File "srch", line 19, in <module>
grab("a/tags1")
File "srch", line 15, in grab
mydict[mylist[0]]=mylist[1]
IndexError: list index out of range

This can be rewritten a little more safely like

mydict = dict(pair.split('=',1)
for pair in mylist
if '=' in pair)

Some of John Machin's caveats still apply:
(2) a[0] is empty or not what you expect (a person's name)
(3) a[1] is empty or not what you expect (a job title)
(consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = '
boss')
(4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...]

to which I'd add

(5) what happens if you have more than one equals-sign in your
item? ("bob=robert=manager" or "bob=manager=big-cheese")

#2 and #3 can be ameliorated a bit by

import string
mydict = dict(
map(string.strip,pair.split('=',1))
for pair in mylist
if '=' in pair)

which at least whacks whitespace off either end of your keys and
values. #4 and #5 require a clearer definition of the problem.

-tkc

This seemed to work for me if you are using 2.4 or greater and
like list comprehension.
dict([ tuple(a.split("=")) for a in mylist[1:-1]])
{'mike': 'manager', 'paul': 'employee', 'tom': 'boss'}

should be faster than looping
 
R

Reedick, Andrew

-----Original Message-----
From: [email protected] [mailto:python-
[email protected]] On Behalf Of John Machin
Sent: Wednesday, January 09, 2008 3:02 PM
To: (e-mail address removed)
Subject: Re: problem of converting a list to dict

A bigger hint:
a=i.split('=')
print "'%s' splits into " % (i), a

consider:
(1) using %r instead of '%s'

Eh, personal preference depending on how sure you are of the
data's type.
(2) omitting the redundant space after 'into'

Some of us coming in from other languages and still aren't used
to the comma adding an unwanted space after everything. I've been
tempted to root around in Python's source code to fix the problem.
(3) losing the redundant () around i

For me, the () is there for readability. Python's sprintf
syntax is odd to begin with, and something like
print "'%s' splits into " % i, a, b, c
means either
1) you really do want to append b and c after the
sprintf, or
print "'%s' splits into " % (a), b, c
2) that the formatting string is missing a few things
print "'%s' splits into " % (a, b, c) ## Ooops!
forgot to change it to "%s %5.2d %6.3f"


*****

The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA622
 
M

Mike Meyer

-----Original Message-----
From: [email protected] [mailto:python-
[email protected]] On Behalf Of John Machin
Sent: Wednesday, January 09, 2008 3:02 PM
To: (e-mail address removed)
Subject: Re: problem of converting a list to dict

A bigger hint:
a=i.split('=')
print "'%s' splits into " % (i), a

consider:
(1) using %r instead of '%s'

Eh, personal preference depending on how sure you are of the
data's type.
(2) omitting the redundant space after 'into'

Some of us coming in from other languages and still aren't used
to the comma adding an unwanted space after everything. I've been
tempted to root around in Python's source code to fix the problem.
(3) losing the redundant () around i

For me, the () is there for readability. Python's sprintf
syntax is odd to begin with, and something like
print "'%s' splits into " % i, a, b, c
means either
1) you really do want to append b and c after the
sprintf, or
print "'%s' splits into " % (a), b, c
2) that the formatting string is missing a few things
print "'%s' splits into " % (a, b, c) ## Ooops!
forgot to change it to "%s %5.2d %6.3f"

In that case, I'd suggest making the right operand a tuple:

print "'%s' splits into" % (i,), a, b, c

which some will argue is good style in any case. Or if you just want
to aide readers not used to python, use the redundant parens to
enforce the default parsing:

print ("'%s' splits into" % i), a, b, c

<mike
 
J

John Machin

-----Original Message-----
From: [email protected] [mailto:python-
[email protected]] On Behalf Of John Machin
Sent: Wednesday, January 09, 2008 3:02 PM
To: (e-mail address removed)
Subject: Re: problem of converting a list to dict
consider:
(1) using %r instead of '%s'

Eh, personal preference depending on how sure you are of the
data's type.

For a start, newbies should not assume that they know anything.
Secondly, even if 100% sure that the object is a string object, using
%r instead of '%s' greatly reduces the chance of confusion caused by
content including tabs, newlines, apostrophes, non-ASCII characters,
etc especially when there are e-mail and news clients adding noise to
the channel.
Some of us coming in from other languages and still aren't used
to the comma adding an unwanted space after everything. I've been
tempted to root around in Python's source code to fix the problem.

There are situations when the space is exactly what is wanted. In
other situations where you need precise control, use file.write and %
formatting. Here's a quick "macro" for retrofreaks:
.... stream.write(format % varargs)
....
For me, the () is there for readability. Python's sprintf
syntax is odd to begin with, and something like
print "'%s' splits into " % i, a, b, c
means either
1) you really do want to append b and c after the
sprintf, or
print "'%s' splits into " % (a), b, c
2) that the formatting string is missing a few things
print "'%s' splits into " % (a, b, c) ## Ooops!
forgot to change it to "%s %5.2d %6.3f"

For readability, consider print ("'%s' splits into " % i), a, b, c
 
M

Matt Nordhoff

bsneddon said:
This seemed to work for me if you are using 2.4 or greater and
like list comprehension.
dict([ tuple(a.split("=")) for a in mylist[1:-1]])
{'mike': 'manager', 'paul': 'employee', 'tom': 'boss'}

should be faster than looping

That's what he's doing (well, a generator expression, not a listcomp).
It's just split across multiple lines (ew).
--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top