473,394 Members | 1,721 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

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(@bars) {
foreach $el_count(@els) {
$var = somefunc($bar_count,$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...thanks.
Jul 18 '05 #1
4 2384
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.man> 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(@bars) {
foreach $el_count(@els) {
$var = somefunc($bar_count,$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_count, 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_count, 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_string} 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*****************@irishsea.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_count, 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*****@hotmail.com> wrote:
...
foreach $bar_count(@bars) {
foreach $el_count(@els) {
$var = somefunc($bar_count,$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_count, el_count)
subdict = data.set_default(bar_count, {})
subdict = subdict.set_default('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
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...
7
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...
17
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...
8
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. ...
11
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...
9
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...
5
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...
2
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...
4
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...

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.