Question

Python Script - Overwriting records


Badge

 

name = feature.getAttribute('Chain')

query = {'Name': name}

params = {'query': json.dumps(query), 'fields': 'Name,Id', "OrderBy": "Name", 'limit': 5}

r = requests.get('https://location.chainxy.com/api/Chains', params=params, headers=headers)

 

for whatever in json.loads(r.content)['Records']:

<space> chainid = whatever['Id']

<space> chainname = whatever['Name']

<space> feature.setAttribute('CXY Name', chainname)

<space> feature.setAttribute('CXY Id', chainid)

------------------------------------------------------------------------------------------

Let's say that my list has three items and I expect my output to be as the following but apparently, my for loop is overwriting my record so I only end up with one record instead of three. How can I fix this problem?

------------------------------------------------------------------------------------------

Expected Output

Record ID --- CXY Name --- CXY Id

1 --- Hello --- 87

1 --- Hi --- 88

1 --- Nice --- 100

 

Actual Output

Record ID CXY Name CXY Id

1 Nice 100


6 replies

Userlevel 2
Badge +17

Hi @trungn1993,

Do you want to create a new feature for each record, or do you you want to create list attributes on the feature?

Badge

Hi @trungn1993,

Do you want to create a new feature for each record, or do you you want to create list attributes on the feature?

How about both :)?

Userlevel 2
Badge +17

How about both :)?

Different processes for each.

Badge

Different processes for each.

I want to create list attributes on the feature.

Userlevel 1
Badge +10

This is the one way you can create a list on an attribute

import fme
import fmeobjects

def processFeature(feature):
    list = ['apple','banana','pear']
    for i, val in enumerate(list):
        feature.setAttribute('list{'+str(i)+'}.fruit',val)

Don't forget to enter the list attribute in the python caller under Attributes to Expose

Userlevel 4

In addition to the reply by @egomm, here's a solution for creating one feature for each element in a Python list:

import fme
import fmeobjects
 
class processFeature(object):
    def input(self, feature):
        list = ['apple','banana','pear']
        for i, val in enumerate(list):
            new_feature = feature.clone()
            new_feature.setAttribute('list_value', val)
            self.pyoutput(new_feature)

This will create a copy of the incoming feature(s) for each element in the list, adding a new attribute "list_value".

Reply