2

I've recently jumped out of the matrix laboratory window and I'm trying to get Python/Numpy/Scipy to do the things I used to do in MatLab. It seems really good so far, but one thing I'm struggling with is finding something similar to the data structure in MatLab.

I want to write a general code for reading in an .xml file and automatically assigning variables into a data structure depending on whether they are strings, scalars or matrices. A typical xml file would be split up like this:

<material>
<id>
1
<\id>
<E>
17e4
<\E>
<var 2>
'C:\data file path'
<\var 2>
<var 3>
[1 2;3 4]
<\var 3>
<\material>
<material>
<id>
2
<\id>
<var 1>
17e4
<\var 1>
<var 2>
'C:\data file path'
<\var 2>
<var 3>
[1 2;3 4]
<\var 3>
<\material>
...
etc

In Matlab I would have created a data structure something like this:

Materials.1.E=17e4
Materials.1.var2='C:\data file path'
Materials.1.var3=[1 2;3 4]
Materials.2.E=17e4
Materials.2.var2='C:\data file path'
Materials.2.var3=[1 2;3 4]

If the list in python could be 2D (so I could have all of the variables for each material on one row) or the dictionary could have more than one layer or could contain lists they'd be perfect but I can't find what I want at the moment!

Any help will be much appreciated!

Peter Greaves
  • 327
  • 5
  • 16
  • 4
    why can't you have a list of dictionaries in python? – Shai Oct 24 '13 at 21:44
  • It might be useful to take a look at [this post](http://stackoverflow.com/questions/1912434/how-do-i-parse-xml-in-python) about parsing XML using Python. Also, if you're working with the Python data analysis stack, I highly - **highly** - recommend getting aquatinted with [iPython](http://ipython.org/) and [pandas](http://pandas.pydata.org/). You can get them both as a part of Continuum Analytics [Anaconda](http://store.continuum.io) Python distribution. – jeremiahbuddha Oct 24 '13 at 22:02

1 Answers1

7

As Shai suggests, you could use a list of dictionaries. For your example this would look something like this:

Materials = []

Materials.append({'E': 17e4, 'var2': 'C:\\data file path', 'var3': [1, 2, 3, 4]})
Materials.append({'E': 17e4, 'var2': 'C:\data file path', 'var3':[1, 2,3, 4]})

print Materials[0]['var2']

which prints:

C:\data file path
Molly
  • 13,240
  • 4
  • 44
  • 45
  • Thanks Molly, that's exactly what I needed. There's nothing in the book I'm learning from on doing this but I knew the information super highway would come through for me! – Peter Greaves Oct 25 '13 at 07:15