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!

2
  • 4
    why can't you have a list of dictionaries in python? Commented Oct 24, 2013 at 21:44
  • It might be useful to take a look at this post about parsing XML using Python. Also, if you're working with the Python data analysis stack, I highly - highly - recommend getting aquatinted with iPython and pandas. You can get them both as a part of Continuum Analytics Anaconda Python distribution. Commented Oct 24, 2013 at 22:02

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.