structure in Python
Ben Caradoc-Davies
ben at wintersun.org
Mon Oct 20 20:53:03 EDT 2003
On Mon, 20 Oct 2003 18:13:48 -0500, Alberto Vera <avera at 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 <ben at wintersun.org>
http://wintersun.org/
Imprisonment on arrival is the authentic Australian immigration experience.
More information about the Python-list
mailing list