Eigenvalue
Eigenvalue

Reputation: 1133

Accessing fields in a yaml file with python

So, ive found other stack overflow codes to get fields and this is what i have a typical .yaml for me looks like this

  - id:
    bioguide: B000226
    govtrack: 401222
    icpsr: 507
  name:
    first: Richard
    last: Bassett
  bio:
    birthday: '1745-04-02'
    gender: M
  terms:
  - type: sen
    start: '1789-03-04'
    end: '1793-03-02'
    state: DE
    class: 2
    party: Anti-Administration

I have about 12000 of these i want to parse though, once i understand one its just a matter of letting it run. Right now im just trying to do something simple like get the name of a person in the file so i tried this

for filename in os.listdir(currentPath):
            print filename
            if(filename.endswith(".yaml")):
                with open(os.path.join(currentPath, filename)) as myFile:
                    results = yaml.load(myFile)
                    try:
                        print results["name"]["first"]
                    except:
                        print "Problem"

If i dont try to catch exceptions i get this issue which im not sure why because isnt a yaml file a dictionary like a json file? Seems like it interprets me as using it as a list.

print results["name"]["first"]
TypeError: list indices must be integers, not str

Im missing something basic, sort of the only obstacle i have is getting the data from the yaml, some insight would much be appreciated

Edit:

When i print one of the files of my 12000 it takes this format

    [{'bio': {'gender': 'M', 'birthday': '1914-06-09'}, 'terms': [{'start': '1963-01-09', 'state': 'CA', 'end': '1964-10-03', 'district': 34, 'party': 'Democrat', 'type': 'rep'}, {'start': '1965-01-04', 'state': 'CA', 'end': '1966-10-22', 'district': 34, 'party':  'Democrat', 'type': 'rep'}, {'start': '1967-01-10', 'state': 'CA', 'end': '1968-10-14', 'district': 34, 'party': 'Democrat', 'type': 'rep'}, {'start': '1969-01-03', 'state': 'CA', 'end': '1971-01-02', 'district': 34, 'party': 'Democrat', 'type': 'rep'}, {'start': '1971-01-21', 'state': 'CA', 'end': '1972-10-18', 'district': 34, 'party': 'Democrat', 'type': 'rep'}, {'start': '1973-01-03', 'state': 'CA', 'end': '1974-12-20', 'district': 34, 'party': 'Democrat', 'type': 'rep'}], 'id': {'bioguide': 'H000164', 'icpsr': 10594, 'house_history': 14486, 'wikipedia': 'Richard T. Hanna', 'thomas': '00494', 'govtrack': 405046}, 'name': {'middle': 'Thomas', 'last': 'Hanna', 'first': 'Richard'}}]

If you can help me and show me how to access some things such as name, start end date etc that would be extremely helpful.

Upvotes: 2

Views: 4055

Answers (1)

Bemmu
Bemmu

Reputation: 18217

Would this work?

try:
  print results[0]['name']['first']
except:
  print 'Problem'

Upvotes: 2

Related Questions