1

I am doing a fairly complex task of reading in a python model and then performing various tasks on it, afterwards that gets written out as individual XML files. However along with this I need to provide various summary file depending on what the individual python model contains.

In Ruby, I would simply store this data in a struct and then parse the array of data. In Python, the dictionary is equivalent to struct, but what's not obvious to me in my testing is how I can add to the values in a dictionary so that if I have:

name: "John"
place: "Atlanta"
age: "18"

All of this neatly fits into a dictionary. But what about the next record?

When I use update, it replaces the dictionary items with the new data. So I thought, I would then use a list to simply append the list with my dictionary data. However, when I append my list (because I used update for the dictionary), my list now contains a list of all the same data.

What is the proper Python way to store multiple dictionary items so they can be accessed later like they are a single record? I thought maybe a tuple but that didn't seem to get me very far either, so I'm obviously doing something very wrong.

FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
Wayne Brissette
  • 135
  • 2
  • 8

1 Answers1

1

I would make a list with dictionaries in them, so the result would be like this:

struct = [{"name": "John", "place": "Atlanta", "age": "18"}, {"name": "Mary", "place": "New York", "age": "22"}]

Then you can for example loop over the list and print the values like this;

for ls in struct:
    print("Name:", ls["name"])
    print("Place:", ls["place"])
    print("Age:", ls["age"])
sundance
  • 2,905
  • 4
  • 21
  • 31
ruohola
  • 21,987
  • 6
  • 62
  • 97
  • This is what I want, but I want to add to the list after each iteration. This is where I'm failing. So In your example, I have the data for John. Then in the next iteration I would have the data for Mary. I'm using a global thinking that would fix it, but if I use: mylist.append(myDictionary) it does add a new list item, but my dictionary items are all changed. again, I think I'm just missing some fundamental thing here. – Wayne Brissette Aug 29 '18 at 14:10