By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,902 Members | 1,409 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,902 IT Pros & Developers. It's quick & easy.

structure in Python

P: n/a
Hello:
I have the next structure:
[key1,value1,value2]

['A',1,5]
['B',6,7]

How Can I make it using Python?

How Can I update the value of 6?
How Can I insert a key called "C" and its values?
How Can I delete a key called "B"?
How Can I search a key called "A"(parameter) and get its values?

Regards
Jul 18 '05 #1
Share this Question
Share on Google+
27 Replies


P: n/a
Dora and Boots say: "Say map! Say map!"
stuff = { 'A' : [1,5], 'B' : [6,7] }
stuff['B'][0] += 6
stuff {'A': [1, 5], 'B': [12, 7]} stuff['C'] = [33,44]
del stuff['B']
print stuff["A"]

[1, 5]

- Matt

"Alberto Vera" wrote:
I have the next structure:
[key1,value1,value2]

How Can I make it using Python?
How Can I update the value of 6?
How Can I insert a key called "C" and its values?
How Can I delete a key called "B"?
How Can I search a key called "A"(parameter) and get its values?

Jul 18 '05 #2

P: n/a
On Mon, 20 Oct 2003 18:13:48 -0500, Alberto Vera <av***@coes.org.pe> wrote:
Hello:
I have the next structure:
[key1,value1,value2]

['A',1,5]
['B',6,7]

How Can I make it using Python?
You could use a dict of lists of length 2.

d = {
"A": [1, 5],
"B": [6, 7], # last trailing comma is optional but good style
}
How Can I update the value of 6?
6 will always be 6, numbers are immutable, and you can't change it. But you can
change the first item of the list with key "B" with

d["B"][0] = 2

now

d["B"]

will return [2, 7]
How Can I insert a key called "C" and its values?
d["C"] = [8, 9]
How Can I delete a key called "B"?
del d["B"]
How Can I search a key called "A"(parameter) and get its values?


d["A"]

You could also use multiple assignment to bind variables to the values with

(value1, value2) = d["A"]

If a key is not found, a KeyError exception is raised. If you prefer, you can
test for the existence of the key with d.has_key("A") . Read the section on
"Mapping types" in the Python Library Reference

http://python.org/doc/lib/lib.html

which describes the methods of dict objects.

--
Ben Caradoc-Davies <be*@wintersun.org>
http://wintersun.org/
Imprisonment on arrival is the authentic Australian immigration experience.
Jul 18 '05 #3

P: n/a
On Mon, 20 Oct 2003 18:13:48 -0500, "Alberto Vera" <av***@coes.org.pe>
wrote:
Hello:
I have the next structure:
[key1,value1,value2]

['A',1,5]
['B',6,7]

How Can I make it using Python?
Use a dictionary with the values in lists:
listdict = {'A': [1, 5], 'B': [6, 7]}
print listdict {'A': [1, 5], 'B': [6, 7]}

How Can I update the value of 6? print listdict['B'][0] 6 listdict['B'][0] = 28
print listdict['B'][0] 28
How Can I insert a key called "C" and its values? listdict['C'] = [1, 2, 3]
print listdict {'A': [1, 5], 'C': [1, 2, 3], 'B': [28, 7]}
How Can I delete a key called "B"? del listdict['B']
print listdict {'A': [1, 5], 'C': [1, 2, 3]}
How Can I search a key called "A"(parameter) and get its values? if 'A' in listdict:

.... print listdict['A']
....
[1, 5]


Regards


Try searching the Python documentation or take the Tutorial:
http://www.python.org/doc/current/tut/tut.html

--
Christopher
Jul 18 '05 #4

P: n/a
On Mon, 20 Oct 2003 18:13:48 -0500, "Alberto Vera" <av***@coes.org.pe> wrote:
This is a multi-part message in MIME format. ^^^^^^^^--try to send only plain text to newsgroups if you can ;-)
Hello:
I have the next structure:
[key1,value1,value2]

['A',1,5]
['B',6,7]

How Can I make it using Python? Lots of ways, so how to do it best will depend on how you intend to use it
and e.g., whether you want to make a collection of them be storable and retrievable
after the computer has been off.
How Can I update the value of 6? Again, how would you like to refer to that 6?
How Can I insert a key called "C" and its values? Do you care about the order you are doing it? Do you expect to see what order they
were put in after you have put in many?
How Can I delete a key called "B"? What if "B" has many records associated with it? How do you want to specify?
How Can I search a key called "A"(parameter) and get its values?

Are you saying you want to be able to match more than the "A" here? Will it
be legal to have ['A',1,5] and ['A',1,55] in the same collection? I.e., is any
key1 going to be unique, or not? Will you want to search for e.g, ['A',1, <wild card indicator>]?

As others have shown, a Python dict using key1 as key and the rest as an associated value list
does the basic job for unique keys. But the order is lost, in case you wanted to know what the
first or last item entered was.

All the things can be done. If you want various behavior for some "box" that you
put this info in, I would suggest defining a class and defining the methods to
do the operations on/with the data that you require.

Regards,
Bengt Richter
Jul 18 '05 #5

P: n/a

"Alberto Vera" <av***@coes.org.pe> wrote in message
news:ma*************************************@pytho n.org...
Hello:
I have the next structure:
[key1,value1,value2]

['A',1,5]
['B',6,7]

How Can I make it using Python?

How Can I update the value of 6?
How Can I insert a key called "C" and its values?
How Can I delete a key called "B"?
How Can I search a key called "A"(parameter) and get its values?
-------------

Have you done the Python tutorial or other beginner material?
Either way, pay more attention to parts about dictionaries.

TJR
Jul 18 '05 #6

P: n/a
Ben Caradoc-Davies wrote:
d = {
"A": [1, 5],
"B": [6, 7], # last trailing comma is optional but good style
}


Why is it considered good style? I mean, I understand that it's easier
to later add a new line, but... Most places (SQL comes first to mind,
since I've just done a lot of work with Python and databases) don't
accept a trailing comma in a similar situation, so if I get into the
habit of including the trailing comma, I'll just end up tripping myself
up a lot.

--
Timo Virkkala

Jul 18 '05 #7

P: n/a
Timo Virkkala wrote:
Ben Caradoc-Davies wrote:
d = {
"A": [1, 5],
"B": [6, 7], # last trailing comma is optional but good style
}
Why is it considered good style? I mean, I understand that it's easier
to later add a new line, but...


Exactly. You'll save a lot of trouble.
Most places (SQL comes first to mind,
since I've just done a lot of work with Python and databases) don't
accept a trailing comma in a similar situation, so if I get into the
habit of including the trailing comma, I'll just end up tripping myself
up a lot.


C, C++, and, I believe, Java all allow such trailing commas too. It's
basically a consensus among modern programming languages (SQL isn't).

Learning to use different style in SQL is not going to be difficult,
because it's such a hugely different language from all of these
anyway. Are you afraid to use a * for multiplication because it may
confuse you to write 'select * from ...'?-)

Plus, there are errors which are either diagnosed by the computer
or innocuous (extra commas are typically that way), and others which
are NOT diagnosed and can be terribly dangerous (missing commas may be).
E.g., consider:

x = [
"fee",
"fie"
"foo",
"fum"
]

print "we have", len(x), "thingies"

This prints "we have 3 thingies" -- as a comma is missing after
"fie", it's automatically JOINED with the following "foo", and
x is actually ['fee', 'fiefoo', 'fum']. VERY insidious indeed
unelss you have very good unit tests (C &c all have just the same
trap waiting for you).

Do yourself a favour: ALWAYS add trailing commas in such cases
in Python, C, C++, etc. The occasional times where you'll do
so in SQL and get your knuckles rapped by the SQL engine, until
you finally do learn to do things differently in the two "sides"
of things (SQL on one side, Python, C or whatever on the other),
will be a minor annoyance; a missing comma might take you a LONG
time to diagnose through its subtly wrong effects - there's just
no comparison.
Alex

Jul 18 '05 #8

P: n/a
>>>
x = [ 'fe' , 'fi' 'fo' , 'fum' , ]

print "we have", len(x), "thingies"

we have 3 thingies

Alex ....

I don't understand how an extra comma at the end
of a sequence is supposed to help with problems
like this where a sequence delimeter, the comma,
has been ommitted in the middle of the sequence ....

I am, of course, grateful to the original coder
for saving me the 42e-19 ergs of energy required
to press the comma key in cases where I would
further extend the sequence at its end, but personally
find this style convention U G L Y and a possible
source of confusion ....

This probably stems from the fact
that my elementary school grammar teacher
would whack me severely about the head and shoulders
if I wrote ....

Uncle Scrooge took Huey, Duey, and Louie,
to the park.

--
Cousin Stanley
Human Being
Phoenix, Arizona

Jul 18 '05 #9

P: n/a

Cousin> I don't understand how an extra comma at the end of a sequence
Cousin> is supposed to help with problems like this where a sequence
Cousin> delimeter, the comma, has been ommitted in the middle of the
Cousin> sequence ....

Today, I write:

weekdays = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
]

An astute reader points out that I forgot Sunday, so I add a line:

weekdays = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
"Sunday"
]

The problem can occur in other ways as well. Suppose you've painfully
constructed a long list (dozens? hundreds?) of string constants (and you're
not smart enough to realize you should initialize the list from a data file)
then decide it would be easier to maintain that growing list if you kept it
sorted.

weekdays = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
]

becomes

weekdays = [
"Friday",
"Saturday",
"Sunday"
"Thursday",
"Wednesday",
"Monday",
"Tuesday",
]

after selecting the rows containing weekdays in Emacs and typing

C-u ESC | sort RET

Allowing and using a trailing comma prevents those sort of subtle mistakes.

Cousin> I am, of course, grateful to the original coder for saving me
Cousin> the 42e-19 ergs of energy required to press the comma key in
Cousin> cases where I would further extend the sequence at its end,
Cousin> but personally find this style convention U G L Y and a
Cousin> possible source of confusion ....

Practicality beats purity. If it's a constant list which you are certain
you will never extend or reorder, feel free to omit that last comma. Also,
if the list is not a list of string constants there's no real harm in
omitting it either, because if you extend or reorder the list and forget to
insert a comma in the right place you'll get a SyntaxError the next time you
import that module. The only case where it's problematic is for lists of
string constants where "abc" "def" is valid syntax. In this case the Python
bytecode compiler can't help you.

Cousin> This probably stems from the fact that my elementary school
Cousin> grammar teacher would whack me severely about the head and
Cousin> shoulders if I wrote ....

Cousin> Uncle Scrooge took Huey, Duey, and Louie,
Cousin> to the park.

Perhaps, but your Python teacher would have praised you. ;-)

Skip

Jul 18 '05 #10

P: n/a
Cousin Stanley wrote:

x = [ 'fe' , 'fi' 'fo' , 'fum' , ]

print "we have", len(x), "thingies"

we have 3 thingies

Alex ....

I don't understand how an extra comma at the end
of a sequence is supposed to help with problems
like this where a sequence delimeter, the comma,
has been ommitted in the middle of the sequence ....


Note that Alex' list was not all on one line, as you have
reformatted it above. In such a case, I would not include
the trailing comma.

In the case of lists formatted with one item per line, I
now always include the trailing comma for just the maintenance
reasons Alex mentions. This is certainly a case where I've
been burned often enough in (older) C because you *could not*
do that, and I'm happy to have it in Python and, now, in C.

-Peter
Jul 18 '05 #11

P: n/a
Skip Montanaro <sk**@pobox.com> wrote previously:
|if the list is not a list of string constants there's no real harm in
|omitting it either, because if you extend or reorder the list and forget to
|insert a comma in the right place you'll get a SyntaxError

Not necessarily:
x = [1, ... -4,
... +5
... -2,
... 7] x

[1, -4, 3, 7]

Which makes the point even stronger, however.

--
mertz@ _/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: \_\_\_\_ n o
gnosis _/_/ Postmodern Enterprises \_\_
..cx _/_/ \_\_ d o
_/_/_/ IN A WORLD W/O WALLS, THERE WOULD BE NO GATES \_\_\_ z e
Jul 18 '05 #12

P: n/a
Alex Martelli wrote:
Timo Virkkala wrote:
Ben Caradoc-Davies wrote:
d = {
"A": [1, 5],
"B": [6, 7], # last trailing comma is optional but good style
}Why is it considered good style? I mean, I understand that it's easier
to later add a new line, but...

[snip] Learning to use different style in SQL is not going to be difficult,
because it's such a hugely different language from all of these
anyway. Are you afraid to use a * for multiplication because it may
confuse you to write 'select * from ...'?-)
Touché. =)
Plus, there are errors which are either diagnosed by the computer
or innocuous (extra commas are typically that way), and others which
are NOT diagnosed and can be terribly dangerous (missing commas may be).
E.g., consider:

x = [
"fee",
"fie"
"foo",
"fum"
]


A good example. I didn't spot that on the first look.

Maybe I should get into the habit of always including the trailing comma
and see where I get. Before this I didn't even know that it was allowed.

--
Timo Virkkala

Jul 18 '05 #13

P: n/a
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

At 2003-10-20T23:13:48Z, "Alberto Vera" <av***@coes.org.pe> writes:
How Can I make it using Python?


Ask your instructor for a tutor? :)
- --
Kirk Strauser
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)

iD8DBQE/lHwx5sRg+Y0CpvERAsKsAJ9gK5wIfdjscVEEPlKhHAu/71PcQwCeOaSa
WG3b9DzmpIgvsUoDtIA8hlw=
=Md0l
-----END PGP SIGNATURE-----
Jul 18 '05 #14

P: n/a

"Timo Virkkala" <a@a.invalid> wrote in message news:bn**********@nyytiset.pp.htv.fi...
Alex Martelli wrote:
Timo Virkkala wrote:
Ben Caradoc-Davies wrote:
d = {
"A": [1, 5],
"B": [6, 7], # last trailing comma is optional but good style
}
Why is it considered good style? I mean, I understand that it's easier
to later add a new line, but...

[snip]
Learning to use different style in SQL is not going to be difficult,
because it's such a hugely different language from all of these
anyway. Are you afraid to use a * for multiplication because it may
confuse you to write 'select * from ...'?-)


Touché. =)
Plus, there are errors which are either diagnosed by the computer
or innocuous (extra commas are typically that way), and others which
are NOT diagnosed and can be terribly dangerous (missing commas may be).
E.g., consider:

x = [
"fee",
"fie"
"foo",
"fum"
]


A good example. I didn't spot that on the first look.

Maybe I should get into the habit of always including the trailing comma
and see where I get. Before this I didn't even know that it was allowed.

--
Timo Virkkala


Another "solution" is just to look at the previous line and check if it has the comma
or not. You'd better get a habit to THINK and not do things mechanically, as others
suggest.

--
Georgy Pruss
E^mail: 'ZDAwMTEyMHQwMzMwQGhvdG1haWwuY29t\n'.decode('base6 4')
Jul 18 '05 #15

P: n/a
Skip Montanaro wrote:
...
Also, if the list is not a list of string constants there's no real harm
in omitting it either, because if you extend or reorder the list and
forget to insert a comma in the right place you'll get a SyntaxError the


Unfortunately there are lots of cases in which juxtaposing two
would-be items gives different results than separating them with a
comma -- e.g. i could have tuples with callable and args:
(
f,
(),
g,
(),
h
(),
k,
()
)

oops, forgot comma after h, so h is called then and there rather
than stashed in the tuple for later processing. Yeah, eventually
you'll probably get an error, but tracking it down will be useless work.

Number literals are another example, if the one before which
you forgot the comma had a sign.

And what about lists?
[
[1],
[0],
[2]
[0],
[3],
[1]
]

Oops, guess what, the third "sub-list" isn't because the fourth sublist
became an index into it instead -- darn, a missing comma.

It's NOT just string literals, alas.

DO use the "redundant" final comma, and live a happier life:-).
Alex

Jul 18 '05 #16

P: n/a
Georgy Pruss wrote:
"Timo Virkkala" <a@a.invalid> wrote in message news:bn**********@nyytiset.pp.htv.fi...
Another "solution" is just to look at the previous line and check if it has the comma
or not. You'd better get a habit to THINK and not do things mechanically, as others
suggest.


Yeah, that's what I have done thus far. =)

I don't know.. I can't recall ever being burned by forgetting a comma..
Whereas I do remember a couple of occasions where I've included a
trailing comma where I shouldn't have (SQL).

--
Timo Virkkala

Jul 18 '05 #17

P: n/a
Cousin Stanley fed this fish to the penguins on Tuesday 21 October 2003
08:23 am:
This probably stems from the fact
that my elementary school grammar teacher
would whack me severely about the head and shoulders
if I wrote ....

Uncle Scrooge took Huey, Duey, and Louie,
to the park.

Depending on the style guide the teacher is using, even "Uncle Scrooge
took Huey, Duey, and Louie to the park" could get marked down... Though
let me state that I've never been comfortable with "Uncle Scrooge took
Huey, Duey and Louie to the park"... I read that as two entities --
Huey is entity one, and some composite "Duey and Louie" is the other
entity. (Hmmm, don't recall the comics, is it Duey or Dewey?)

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Bestiaria Home Page: http://www.beastie.dm.net/ <
Home Page: http://www.dm.net/~wulfraed/ <


Jul 18 '05 #18

P: n/a
Timo Virkkala <a@a.invalid> wrote in message news:<bn**********@nyytiset.pp.htv.fi>...
Georgy Pruss wrote:
"Timo Virkkala" <a@a.invalid> wrote in message news:bn**********@nyytiset.pp.htv.fi...
Another "solution" is just to look at the previous line and check if it has the comma
or not. You'd better get a habit to THINK and not do things mechanically, as others
suggest.


Yeah, that's what I have done thus far. =)

I don't know.. I can't recall ever being burned by forgetting a comma..
Whereas I do remember a couple of occasions where I've included a
trailing comma where I shouldn't have (SQL).


In SQL statements this seems to be common practice:

select firstname
,lastname
,address
from ...

to avoid getting hurt...

--
Christopher
Jul 18 '05 #19

P: n/a
Skip ...

Thanks for the info ....

In the case where an addition is made to the end
of a L O N G sequence and then followed by a resort,
I can see that depending on how the sequence is used
that problems arising from inadvertent omission of
the comma delimeter by whomever extended the sequence
might not manifest themselves immediately and could
perhaps be difficult to spot ....

In spite of my Python teacher's praise for using this style,
I would probably still wonder how he/she managed to make it
through school without getting whacked for using it themselves ....

--
Cousin Stanley
Human Being
Phoenix, Arizona

Jul 18 '05 #20

P: n/a
Peter ....

Thanks for the reply ....

I usually format long lists as one item per line as well ....

I only stuck Alex' example on a single line
since it was short and I was using the interpreter ....

The style that looks the most natural and seems the easiest
to extend and edit to me is ....

x = [ 'fe' ,
'fi' ,
'fo' ,
'fum' ]

--
Cousin Stanley
Human Being
Phoenix, Arizona

Jul 18 '05 #21

P: n/a
| Depending on the style guide the teacher is using,
| even "Uncle Scrooge took Huey, Duey, and Louie to the park"
| .... "Uncle Scrooge took Huey, Duey and Louie to the park"
| ....

Dennis ....

Thanks for the reply ....

This style difference also occurred to me
after I posted the example ....

I think I remember it being taught
that it is a grammatical option
and correct in either case ....

I always include the _final_ comma in these cases myself,
as it usually seems harder to read and potentially confusing
without it ....

--
Cousin Stanley
Human Being
Phoenix, Arizona

Jul 18 '05 #22

P: n/a
> > Timo Virkkala wrote:
Maybe I should get into the habit of always including the
trailing comma and see where I get. Before this I didn't
even know that it was allowed.
Georgy Pruss wrote:
Another "solution" is just to look at the previous line and
check if it has the comma or not. You'd better get a habit to
THINK and not do things mechanically, as others suggest.


It is better to think and not do things mechanically, and that's exactly why
people add the trailing comma.

If you do things mechanically, you may leave out the trailing comma, because
it certainly isn't necessary.

If you think about making your code maintainable, you will look for ways to
prevent mistakes when people edit your code later. The trailing comma helps
prevent mistakes, so you'll use it.

-Mike
Jul 18 '05 #23

P: n/a
Michael Geary wrote:
Timo Virkkala wrote:
Maybe I should get into the habit of always including the
trailing comma and see where I get. Before this I didn't
even know that it was allowed.
Georgy Pruss wrote:
Another "solution" is just to look at the previous line and
check if it has the comma or not. You'd better get a habit to
THINK and not do things mechanically, as others suggest.


It is better to think and not do things mechanically, and that's exactly why
people add the trailing comma.

If you do things mechanically, you may leave out the trailing comma, because
it certainly isn't necessary.


While I agree with your point, which is that putting *in* the trailing
comma is the result of a great deal of thought in advance (such as we're
doing right now), I have to disagree with your explanation for what
"mechanical" would imply.

Mechanical would be more appropriately used when you do the same thing
over and over, completely without having to think. The mere fact that
you say "because it isn't necessary" shows that thought had to be involved
(to evaluate the need for the comma) and therefore it's not mechanical.
If you think about making your code maintainable, you will look for ways to
prevent mistakes when people edit your code later. The trailing comma helps
prevent mistakes, so you'll use it.


Quite true!
Jul 18 '05 #24

P: n/a
Cousin Stanley wrote:
The style that looks the most natural and seems the easiest
to extend and edit to me is ....

x = [ 'fe' ,
'fi' ,
'fo' ,
'fum' ]


Other people have raised some good points as to why using
trailing commas can be better, but for my money the best
reason to consistently use trailing commas is how a CVS
(or other) diff will look later. You can either see
one deleted line plus two added lines, or a single added
line, your choice.

Pat
Jul 18 '05 #25

P: n/a

"Patrick Maupin" <pm*****@speakeasy.net> wrote in message news:65**************************@posting.google.c om...
Cousin Stanley wrote:
The style that looks the most natural and seems the easiest
to extend and edit to me is ....

x = [ 'fe' ,
'fi' ,
'fo' ,
'fum' ]


Other people have raised some good points as to why using
trailing commas can be better, but for my money the best
reason to consistently use trailing commas is how a CVS
(or other) diff will look later. You can either see
one deleted line plus two added lines, or a single added
line, your choice.

Pat


You can always find a better diff which will show you an added
comma and an additional line. Again, it's a tool problem.

Georgy
Jul 18 '05 #26

P: n/a
Georgy Pruss wrote:
You can always find a better diff which will show you an added
comma and an additional line. Again, it's a tool problem.


Do not presume, simply because I choose to arrange my affairs
such that I can usually use a BB gun more effectively than many
can use a howitzer, that I have a "tool problem."

Pat
Jul 18 '05 #27

P: n/a
| ...
| the best reason to consistently use trailing commas
| is how a CVS (or other) diff will look later.
| You can either see one deleted line plus two added lines,
| or a single added line, your choice.

Patrick ....

Thanks for the info ....

I'm not currently using versioning tools
as I'm only a single developer and most
of my code at this point is very simple
and a backup copy or two usally work OK for me ....

However, I will keep this in mind for the future ....

--
Cousin Stanley
Human Being
Phoenix, Arizona

Jul 18 '05 #28

This discussion thread is closed

Replies have been disabled for this discussion.