pythonsyntaxmarc

python: how to create list of/iterate through multiple instances of a variable


I am working with the pymarc library. My question is, how to I deal with multiple instances of a variable, either building a list, or otherwise iterating through them?

A MARC field can be accessed by adding the field number to the record variable. For instance, I have three instances of an 856 field in one record, which can be accessed as record['856']. But only the first instance is passed.

assigning a variable record['856'][0] or record['856'][1] etc, doesn't work.

I have tried creating a list, which is shown below, but that didn't work

from pymarc import MARCReader

with open('file.mrc', 'rb') as fh:
    reader = MARCReader(fh)
    for record in reader: 
            """get all 856 fields  -- delete unwanted 856 fields
            =856  40$uhttp://url1.org
            =856  40$uhttp://url2.org
            =856  40$uhttp://url3.org
            """
                eight56to956s = []
                eight56to956 = record['856']
                eight56to956s.append(eight56to956)
                print eight56to956s

I know how I would do this in php, but I'm not getting my head around python syntax to even search the web for the right thing.


Solution

  • You need a dictionary, where you can set 856 as the key and then a list of values you want to be tagged to 856

    your_856 = {856: ['=856  40$uhttp://url1.org', '=856  40$uhttp://url2.org', '=856  40$uhttp://url3.org']}
    

    you can now access the values like with an index, here is an Example

    print(your_856[856][1])
    

    this outputs

    =856  40$uhttp://url2.org