473,396 Members | 2,111 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

problem of converting a list to dict

Hi pals

I have a list like this

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

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
Jan 9 '08 #1
11 1546
On Wed, 09 Jan 2008 10:56:36 -0800, Louis.Soninhu wrote:
Hi pals

I have a list like this

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

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','mean ingless']

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
Jan 9 '08 #2
Lo***********@gmail.com wrote:
I have a list like this

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

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>

Jan 9 '08 #3
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
Jan 9 '08 #4
On Jan 9, 3:05*pm, Fredrik Lundh <fred...@pythonware.comwrote:
Louis.Soni...@gmail.com wrote:
I have a list like this
mylist=['','tom=boss','mike=manager','paul=employee','mean ingless']
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
Jan 9 '08 #5
Lo***********@gmail.com wrote:
>to see what's going on on your machine, try printing "a" after the
split, but before you use it to populate the dictionary.

'print a' works
so what does it tell you?

</F>

Jan 9 '08 #6
-----Original Message-----
From: py********************************@python.org [mailto:python-
li*************************@python.org] On Behalf Of Fredrik Lundh
Sent: Wednesday, January 09, 2008 2:39 PM
To: py*********@python.org
Subject: Re: problem of converting a list to dict

Lo***********@gmail.com wrote:
to see what's going on on your machine, try printing "a" after the
split, but before you use it to populate the dictionary.
'print a' works
so what does it tell you?
A bigger hint:
a=i.split('=')
print "'%s' splits into " % (i), a
assert len(a) == 2
mydict[a[0]]=a[1]
Jan 9 '08 #7
oops, it seems there are other 'meaningless' item, which actually
caused the problem

Thanks for helps
Jan 9 '08 #8
On Jan 10, 6:52 am, "Reedick, Andrew" <jr9...@ATT.COMwrote:
-----Original Message-----
From: python-list-bounces+jr9445=att....@python.org [mailto:python-
list-bounces+jr9445=att....@python.org] On Behalf Of Fredrik Lundh
Sent: Wednesday, January 09, 2008 2:39 PM
To: python-l...@python.org
Subject: Re: problem of converting a list to dict
Louis.Soni...@gmail.com wrote:
>to see what's going on on your machine, try printing "a" after the
>split, but before you use it to populate the dictionary.
'print a' works
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]
Jan 9 '08 #9
On Wed, 9 Jan 2008 14:34:26 -0600 "Reedick, Andrew" <jr****@ATT.COMwrote:
-----Original Message-----
From: py********************************@python.org [mailto:python-
li*************************@python.org] On Behalf Of John Machin
Sent: Wednesday, January 09, 2008 3:02 PM
To: py*********@python.org
Subject: Re: problem of converting a list to dict

On Jan 10, 6:52 am, "Reedick, Andrew" <jr9...@ATT.COMwrote:
>
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
--
Mike Meyer <mw*@mired.org> http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.
Jan 9 '08 #10
On Jan 10, 7:34 am, "Reedick, Andrew" <jr9...@ATT.COMwrote:
-----Original Message-----
From: python-list-bounces+jr9445=att....@python.org [mailto:python-
list-bounces+jr9445=att....@python.org] On Behalf Of John Machin
Sent: Wednesday, January 09, 2008 3:02 PM
To: python-l...@python.org
Subject: Re: problem of converting a list to dict
On Jan 10, 6:52 am, "Reedick, Andrew" <jr9...@ATT.COMwrote:
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.
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.
>
(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.
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:
>>def fprintf(stream, format, *varargs):
.... stream.write(format % varargs)
....
>>import sys
fprintf(sys.stdout, "strg:%s int:%d\n", 'foo', 42)
strg:foo int:42
>>>
>
(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"
For readability, consider print ("'%s' splits into " % i), a, b, c

Jan 9 '08 #11
bsneddon wrote:
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).
--
Jan 9 '08 #12

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

Similar topics

2
by: ajikoe | last post by:
Hi, I tried to follow the example in swig homepage. I found error which I don't understand. I use bcc32, I already include directory where my python.h exist in bcc32.cfg. /* File : example.c...
5
by: metaperl.etc | last post by:
The following program does not work if you uncomment #lis = + list(args) Evidently Python is opting for the nullary constructor list() as opposed to the other one which takes a sequence....
1
by: rieh25 | last post by:
If I have a dictionary such as: d = {'a' : 1, 'b' : 2} is there a way to convert it into an object o, such as: o.a = 1 o.b = 2 thanks
4
by: Emin | last post by:
Dear Experts, How much slower is dict indexing vs. list indexing (or indexing into a numpy array)? I realize that looking up a value in a dict should be constant time, but does anyone have a...
9
by: Samuel | last post by:
Hi, is there a short version for this? res_dict = {} for resource in res_list: res_dict = resource This does not work:
3
by: ZMY | last post by:
I am new to Numpy/Pylab, and I am trying to construct a list of dictionaries with arrays as the items, for example: .... ), 2: ''}, {1: array(), 2: ''}, {1: array(), 2: ''}] ), 2: ''}, {1:...
20
by: Seongsu Lee | last post by:
Hi, I have a dictionary with million keys. Each value in the dictionary has a list with up to thousand integers. Follow is a simple example with 5 keys. dict = {1: , 2: , 900000: , 900001:...
0
by: Gabriel Genellina | last post by:
En Fri, 19 Sep 2008 10:59:26 -0300, Ron Brennan <brennan.ron@gmail.com> escribió: I guess you probably tried using ' '.join(value) and got an error like this: TypeError: sequence item 0:...
3
by: rewonka | last post by:
Hello, I'm trying to find the fastest way to convert an sql result into a dict or list. What i mean, for example: my sql result: contact_id, field_id, field_name, value sql_result=, , ,
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.