0

I'm pulling from an xml file using etree where I've extracted the following from a tag called dc as text:

<dc>[{"name": "Smith", "affiliation": "UofHawaii"}, {"name": "Doe", "affiliation": "UW"}]</dc>

so I have dc = [{"name": "Smith", "affiliation": "UofHawaii"}, {"name": "Doe", "affiliation": "UW"}]

I want to parse this out to have names and affiliations as lists:

names = Smith, Doe
affiliations = UofHawaii, UW

Is there a simple way to do this? I can see that it's similar to a dictionary but not quite. The number of names and affiliations does vary in the tree from 1 to 4.

Thanks.

KDougler
  • 11
  • 3
  • 5
    Possible duplicate of [How to merge multiple dicts with same key?](https://stackoverflow.com/questions/5946236/how-to-merge-multiple-dicts-with-same-key) – miradulo Dec 04 '17 at 20:15
  • I expect that string is intended to be read as JSON data, so use the `json` module to parse it. If it's supposed to be Python code (which is sometimes identical), you could perhaps instead use `ast.literal_eval`. Once you have the list of dicts in Python, you can use the answers to the linked question. – Blckknght Dec 04 '17 at 20:22

1 Answers1

1

Simple list-comp.

names = [x["name"] for x in dc]
affiliations = [x["affiliation"] for x in dc]

>>> names
['Smith', 'Doe']
>>> affiliations
['UofHawaii', 'UW']