简体   繁体   中英

Python lambda expression - string indices must be integers

I am trying to use data from one json file to update another. In trying to be efficient for searching, I'm attempting to use a lambda expression to locate the correct record to update.

The goal is to be able to most efficiently update the "PreviousMappings" key.

Code:

for p in Path('jobs/data').glob('*.json'):
        with open(p, 'r') as f:
            print('Loaded - ', f.name)
            jdata = json.load(f)
            for j in jdata['Mappings']:
                jc = j['Job Code']
                with open('newdata/jobs.json', 'r+') as s:
                    print('Loaded - ', s.name)
                    data = json.load(s)
                    found = list(filter(lambda x:x['Jobcode'] == jc, data)) #throws exception

JSON:

      {
"JobCodes": [
            {
                "Bid Code": "123-456",
                "Description": "JOB DESCRIPTION",
                "Jobcode": "ABC123",
                "PreviousMappings": ""
            }
    ]
}

This does what you're asking, but you might consider a different approach.

data = json.load( open('newdata/jobs.json', 'r')  )

for p in Path('jobs/data').glob('*.json'):
    with open(p, 'r') as f:
        print('Loaded - ', f.name)
        jdata = json.load(f)
        for j in jdata['Mappings']:
            jc = j['Job Code']
            for k in data:
                if k['Jobcode'] == jc:
                    k['PreviousMappings'] = "something"
                    break

json.dump( open('newdata/jobs.json','w'), data )

If you have a LOT of files, you might consider building an index, so you can do a direct lookup. For example (untested):

data = json.load( open('newdata/jobs.json', 'r')  )
dindex = {}
for k in data:
    dindex[k['Jobcode']] = k

Now you don't have to search -- Python will do it:

        for j in jdata['Mappings']:
            jc = j['Job Code']
            if jc in dindex:
                dindex[jc]['PreviousMappings'] = "something"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM