Find index of item in a list of tuples

Find index of item in a list of tuples

book

Article ID: KB0079984

calendar_today

Updated On:

Products Versions
TIBCO Streaming -

Description

Given a list of tuples, how can I find which element has an inner tuple field with a given value?

Issue/Introduction

Using StreamBase Expression Language function unzip()

Resolution

A list of tuples would appear to be a complex data structure to search. A common use of this structure are for Name/Value pairs to hold named elements which do not appear within regular schema. Name/Value pairs in SB are best represented as type:
  list(tuple(Name string, Value string))
There is a zero-cost function, unzip(), which turns this data structure into:
  tuple(list(Name string),list(Value string))
while keeping element order. This means that searching a single list can now produce an index into the full data-structure at that index. The unzip() (and the inverse, zip()) function has zero computational cost because it merely produces a different view into the list data-structure at compile time.

The string type is used because strings can hold a representation of any type.

Example:

1. Create the named schema: PairsSch(Name string, Value string)

2. Create a field in the input tuple: NVPairsList list(PairsSch)

3. Add Map expressions (use Input Fields = None):

  1) Get the index in "name" list:
    Declare, ind, indexof(unzip(NVPairsList).Name,name)

  2) Report the value at that index from "value" list:
    Add, value, unzip(NVPairsList).Value[ind]

  3) Optionally report the index value:
    Add, index, ind

As so:
Studio Map setup for finding index of element in list of tuple

I set this up using list {'NVPairsList':[{'Name':'Alice','Value':'32'},{'Name':'Bob','Value':'41'},{'Name':'Chris','Value':'38'}]} (the JSON representation of list(Name,Value)).

When running, inputs and outputs are:
1. Input: name=Bob; Map Output: {'value':'41','index':1}
2. Input: name=Alice; Map Output: {'value':'32','index':0},
3. Input: name=Doug; Map Output:  value=null, index=null. No JSON representation. 

For reference, here's the "View Source" Map Definition:
 <box name="Map" type="map">     <input port="1" stream="InputStream"/>     <output port="1" stream="OutputStream"/>     <target-list>         <item name="input" selection="all"/>         <expressions>             <declare field="ind">indexof(unzip(NVPairsList).Name,name)</declare>             <include field="value">unzip(NVPairsList).Value[ind]</include>             <include field="index">ind</include>         </expressions>     </target-list> </box>