473,592 Members | 2,893 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

structure in Python

Hello:
I have the next structure:
[key1,value1,val ue2]

['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"(paramet er) and get its values?

Regards
Jul 18 '05 #1
27 4549
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,val ue2]

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"(paramet er) and get its values?

Jul 18 '05 #2
On Mon, 20 Oct 2003 18:13:48 -0500, Alberto Vera <av***@coes.org .pe> wrote:
Hello:
I have the next structure:
[key1,value1,val ue2]

['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"(paramet er) 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
On Mon, 20 Oct 2003 18:13:48 -0500, "Alberto Vera" <av***@coes.org .pe>
wrote:
Hello:
I have the next structure:
[key1,value1,val ue2]

['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"(paramet er) 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
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,val ue2]

['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"(paramet er) 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

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

['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"(paramet er) 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
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
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
>>>
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

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

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

Similar topics

1
2073
by: lenk | last post by:
Hi all, I want to learn the data structure of python array, is there any website or book for learning thanks
3
5358
by: Ksenia Marasanova | last post by:
I get this kind of list from a database. (The tuple structure is: id, name, parent_id) I would like to transfer it (in Python) into a tree structure. I don't care much about format, as long as I'll be able to get all the information, based on one id. For example, if I have id=3, I want to get - name ('otherparent')
3
1824
by: Dongsheng Ruan | last post by:
Not quite related with Python. But my Data Structure course is experiemented on python and there is no data structure group, So I have to post here: Write a procedure (in pseudocode!) to increase the number of buckets in a (closed) hash table. Analyze its time and space complexity.
4
4082
by: Sergei Minayev | last post by:
Hi All! Can you please help me with the following problem: I need to store a copy of local folders structure in MySQL database. I have chosen the following table structure for that: ------------------------------------------------ | id | id_uplink | folder_name | ------------------------------------------------ id - unique property of each folder. id_uplink - id of upper level folder is stored here (for example: if id of c:\test...
3
2546
by: Thorsten Kampe | last post by:
Hi, This is a fairly general question: is there some kind of module or framework that allows building a tree like structure from certain kind of data? To be specific: I have a program that dumps the content of a LDAP directory including all properties and values and groups the result from the LDAP search by objClass.
0
1167
by: nimitsis | last post by:
Hello I am trying to convert and manage a simple structure C ,to Python by using C. The code is the following : /* example.c*/ double sum(Vector c) { return c.x+c.y+c.z; } /*header.h*/ struct Vector{ double x,y,z;
1
2543
by: nimitsis | last post by:
Hello I am trying to convert and manage a simple structure C ,to Python by using SWIG. The code is the following : /* example.c*/ double sum(Vector c) { return c.x+c.y+c.z; } /*header.h*/ struct Vector{ double x,y,z;
3
955
by: sp | last post by:
Hi there, I'm new to Python and I've been writing a rudimentary exercise in Deitel's Python: How to Program, and I found that this code exhibits a weird behavior. When I run the script, the for...range(1,11) structure always starts with zero--and I've tried plugging other values as well! From the Python commandline, though, this structure produces a normal 1,2,3,4,5,6,7,8,9,10 output. Can anyone tell me what I am doing wrong here?
10
3469
by: Hongtian | last post by:
Hi friends, I am a newer of Python. I want to ask below question: I have a C/C++ application and I want to use Python as its extension. To do that, I have to transfer some data structure from C/C++ application to Python and get some data structure from Python to C/C++ application. I have researched Python document, but the example only describes how to transfer some simple data, such as integer,char, etc.
13
2278
by: Rafe | last post by:
Hi, I am in a situation where I feel I am being forced to abandon a clean module structure in favor of a large single module. If anyone can save my sanity here I would be forever grateful. My problem is that classes in several modules share a common base class which needs to implement a factory method to return instances of these same classes.
0
7871
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8236
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8366
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7995
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8227
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6642
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
2379
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1467
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.