473,602 Members | 2,846 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

complex data structure - insert value

I'm converting a Perl script to Python and have run into something I'm
not sure how to do in Python.

In Perl, I am running through a couple loops and inserting values
directly into a complex data structure (array->hash->array). This
isn't the actual code, but should demonstrate the general idea:

foreach $bar_count(@bar s) {
foreach $el_count(@els) {
$var = somefunc($bar_c ount,$el_count) ;
$data[$bar_count]->{'CC'}->[$el_count] = $var;
}
}

Basically I'd like to do the same thing in Python. I've written a
convoluted test script where I can print an element:

print data[0]['CC'][1]

but I can't insert directly like I do in Perl (data[0]['CC'][1] =
$var). In my test script I've simply initialized my lists and
dictionary at the beginning of the script, not by iterating an
inserting values as in the Perl example.

Any advice appreciated...t hanks.
Jul 18 '05 #1
4 2398
spar wrote:
Basically I'd like to do the same thing in Python. I've written a
convoluted test script where I can print an element:

print data[0]['CC'][1]

but I can't insert directly like I do in Perl (data[0]['CC'][1] =
$var).


This should work fine, though in python this would result in assignment, not
insertion:

*************** ************
#Assignment:
x=[{'foo':[1,2,3]}]
x[0]['foo'][1] = 'bar'
x [{'foo': [1, 'bar', 3]}]
#Insertion:
x[0]['foo'].insert(2, 'baz')
x

[{'foo': [1, 'bar', 'baz', 3]}]

*************** ************

Jeffrey
Jul 18 '05 #2
Jeffrey Froman <je*****@fro.ma n> wrote:
spar wrote:
Basically I'd like to do the same thing in Python. I've written a
convoluted test script where I can print an element:

print data[0]['CC'][1]

but I can't insert directly like I do in Perl (data[0]['CC'][1] =
$var).


This should work fine, though in python this would result in assignment, not
insertion:
#Assignment:
x=[{'foo':[1,2,3]}]
x[0]['foo'][1] = 'bar'
x [{'foo': [1, 'bar', 3]}]
#Insertion:
x[0]['foo'].insert(2, 'baz')
x [{'foo': [1, 'bar', 'baz', 3]}]


The OP is relying on a perl feature called auto-vivification. In perl
speak when you do

$data->[0]->{'CC'}->[1] = "spam";

The only thing that has to exist is the array reference in $data.
Perl will then auto-vivify the hash then the second arrayref.

Python doesn't do this in its standard list and dict objects. So
either you create some subclasses which do (which isn't that hard -
need to overload __setitem__ in both cases and do the perl thing).

Alternatively you can do it the python way... The original

foreach $bar_count(@bar s) {
foreach $el_count(@els) {
$var = somefunc($bar_c ount,$el_count) ;
$data[$bar_count]->{'CC'}->[$el_count] = $var;
}
}

becomes

def somefunc(a,b): return 1
bars=[1, 2, 3, 4, 5]
els=[7, 8]

data = []
for bar_count in bars:
for el_count in els:
var = somefunc(bar_co unt, el_count)
while bar_count >= len(data):
data.append({})
l = data[bar_count].setdefault('CC ', [])
while el_count >= len(l):
l.append(None)
l[el_count] = var

pprint(data) [{},
{'CC': [None, None, None, None, None, None, None, 1, 1]},
{'CC': [None, None, None, None, None, None, None, 1, 1]},
{'CC': [None, None, None, None, None, None, None, 1, 1]},
{'CC': [None, None, None, None, None, None, None, 1, 1]},
{'CC': [None, None, None, None, None, None, None, 1, 1]}]
Or you may prefer this which you can't do in perl (because keys of
hashes can only be strings)

data = {}
for bar_count in bars:
for el_count in els:
var = somefunc(bar_co unt, el_count)
data[(bar_count,'CC' ,el_count)] = var
pprint(data)

{(1, 'CC', 7): 1,
(1, 'CC', 8): 1,
(2, 'CC', 7): 1,
(2, 'CC', 8): 1,
(3, 'CC', 7): 1,
(3, 'CC', 8): 1,
(4, 'CC', 7): 1,
(4, 'CC', 8): 1,
(5, 'CC', 7): 1,
(5, 'CC', 8): 1}

It does't produce quite the same data structures but it may be useful
for you.

However one thing I've noticed from converting quite a few perl
programs to python is that constant 'CC' in a hash is indicative of
the fact that you really should be defining a class, of which CC
becomes an attribute or method. In perl the way is to define complex
data structures of hashes and lists, but in python because its so much
easier to create a class when you want it, do that.

So whenever you see $hash->{constant_stri ng} you should be thinking -
hmm shouldn't that be a class. And when you've made it a class you'll
find that you have functions which should be methods of that class,
and before you know it you'll find your program looks a lot tidier!

--
Nick Craig-Wood <ni**@craig-wood.com> -- http://www.craig-wood.com/nick
Jul 18 '05 #3
Nick Craig-Wood <ni**@craig-wood.com> wrote in message news:<sl******* **********@iris hsea.home.craig-wood.com>...
def somefunc(a,b): return 1
bars=[1, 2, 3, 4, 5]
els=[7, 8]

data = []
for bar_count in bars:
for el_count in els:
var = somefunc(bar_co unt, el_count)
while bar_count >= len(data):
data.append({})
l = data[bar_count].setdefault('CC ', [])
while el_count >= len(l):
l.append(None)
l[el_count] = var

pprint(data)

[{},
{'CC': [None, None, None, None, None, None, None, 1, 1]},
{'CC': [None, None, None, None, None, None, None, 1, 1]},
{'CC': [None, None, None, None, None, None, None, 1, 1]},
{'CC': [None, None, None, None, None, None, None, 1, 1]},
{'CC': [None, None, None, None, None, None, None, 1, 1]}]

Thanks, this is close...I'll have to play with it a bit. I've done
Perl for quite sometime, but am new to Python.

My example code didn't exactly show what I'm trying to do. The data
structure should actually look something like this (think of each
array element as a musical bar, each dict element ('HH', etc.) is an
instrument in that bar, and the list within the dict represent beats
for that instrument within the bar):

[{},
{'CC': ['-', '-', '-', '-'], 'HH': ['x', 'x', 'x', 'x'], 'SD': ['-',
'-', 'o', '-']},
{'CC': ['x', '-', '-', '-'], 'HH': ['x', 'x', 'x', 'x'], 'SD': ['o',
'-', 'o', '-']},
{'CC': ['-', '-', '-', '-'], 'HH': ['x', 'x', 'x', 'x'], 'SD': ['-',
'-', 'o', '-']},
{'CC': ['x', '-', '-', '-'], 'HH': ['x', 'x', 'x', 'x'], 'SD': ['o',
'-', 'o', '-']}]

So this shows bars 1-4 (there is no bar 0, so it's empty), each bar
has three instruments ('CC', 'HH', and 'SD') and each instrument shows
what is to be played on beats (subdivisions) 1-4 (actually there will
be 16 subdivisions representing 16 16th notes).

I think I can take your code and mold it into what I need. Thanks...
Jul 18 '05 #4
spar <sp*****@hotmai l.com> wrote:
...
foreach $bar_count(@bar s) {
foreach $el_count(@els) {
$var = somefunc($bar_c ount,$el_count) ;
$data[$bar_count]->{'CC'}->[$el_count] = $var;
}
}


Not quite sure what you mean, but maybe s/thing like...:

data = {}

for bar_count in bars:
for el_count in els:
var = somefunc(bar_co unt, el_count)
subdict = data.set_defaul t(bar_count, {})
subdict = subdict.set_def ault('CC', {})
subdict[el_count] = var

....?
Alex
Jul 18 '05 #5

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

Similar topics

3
2370
by: Mike Jones | last post by:
need help with data structures.Looking for ways to start, sample code, anything Program description: Design and implement a Visual C++ .NET program that inserts values into a data structure and then removes them as described below.
7
3908
by: mittal.pradeep | last post by:
What is the better table design for a data collection application. 1. Vertical model (pk, attributeName, AttributeValue) 2. Custom columns (pk, custom1, custom2, custom3...custom50) Since the data elements collected may change year over year, which model better takes of this column dynamicness
17
3138
by: Chris Travers | last post by:
Hi all; I just made an interesting discovery. Not sure if it is a good thing or not, and using it certainly breakes first normal form.... Not even sure if it really works. However, as I am able to CRASH the backend, there is a bug here somewhere... test=# select version(); version
8
2953
by: Steve Jorgensen | last post by:
Mailing List management is a good example of a case where my conundrum arises. Say there is a m-m relationship between parties and groups - anyone can be a member of any combintation of groups. Now, let's say the user wants to be able to send mailings to people who have various combinations of membership and non-membership in those groups. Here's a medium-complex example: (Knitting Group or Macrame Group) and Active Contact and Mailing...
11
3597
by: hoopsho | last post by:
Hi Everyone, I am trying to write a program that does a few things very fast and with efficient use of memory... a) I need to parse a space-delimited file that is really large, upwards fo a million lines. b) I need to store the contents into a unique hash. c) I need to then sort the data on a specific field. d) I need to pull out certain fields and report them to the user.
9
2039
by: jardar.maatje | last post by:
I am logging scientific data. For this a normal relationship database is not idéal but I am going to try it. I have basically three tables like: datarecord: * idx - integer * time - datetime * type - integer
5
1472
by: doamud | last post by:
Hello all, I've been trying to reengineer some C code to C++, but got stuck on some complex data structure: On the C code, there is an "Model" struct used to store various kind of data, the exact kind stored in the "type" member. Each kind has different data, that is stored in a "value" array. So, if a Model is type "Car", the maximum speed is stored in value. If it's a "House", value is used to store number of inhabitants. A huge mess!...
2
1710
by: =?Utf-8?B?c2lwcHl1Y29ubg==?= | last post by:
Have a complex process where I need to Import a large amount of data then run some transformations on this data then import into DataBase. The transformation involves multiple fields and multiple process - so the data needs to be read in 1 record at a time then run thru the transformation that may create new data value then everything is imported into a db to store. I have multiple questions 1)we used to have an internal data structure...
4
1427
by: obtrs | last post by:
i have alot of check boxes and through that check boxex one select seat and send tha seat number to database. i have a table named called trip in which i have some fields which are ok but they are on the start page user send booking time and selects "from" "to" after sending that there is a page of seat selection when ever im sending data of seat selection it sends data to the other line how can i send that too on the same line as the others...
0
7993
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8401
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...
1
8054
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
6730
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...
0
5440
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3900
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3944
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1510
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1254
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.