structure in Python

A

Alberto Vera

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
 
M

Matt Gerrans

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

:
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?
 
B

Ben Caradoc-Davies

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.
 
C

Christopher Koppler

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?
.... print listdict['A']
....
[1, 5]


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

Bengt Richter

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
 
T

Terry Reedy

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
 
T

Timo Virkkala

Ben said:
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.
 
A

Alex Martelli

Timo said:
Ben said:
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
 
C

Cousin Stanley

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.
 
S

Skip Montanaro

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
 
P

Peter Hansen

Cousin said:
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
 
L

Lulu of the Lotus-Eaters

|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:
... -4,
... +5
... -2,
... 7] [1, -4, 3, 7]

Which makes the point even stronger, however.
 
T

Timo Virkkala

Alex said:
Timo said:
Ben said:
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.
 
K

Kirk Strauser

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Alberto Vera said:
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-----
 
G

Georgy Pruss

Timo Virkkala said:
Alex said:
Timo said:
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.

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.
 
A

Alex Martelli

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
 
T

Timo Virkkala

Georgy said:
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).
 
D

Dennis Lee Bieber

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?)

--
 
C

Christopher Koppler

Timo Virkkala said:
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...
 
C

Cousin Stanley

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 ....
 

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
474,169
Messages
2,570,918
Members
47,458
Latest member
Chris#

Latest Threads

Top