Lists, Dictionaries, and Indexing
Formulas can work with structured data including lists, dictionaries, tuples, and sets. These collection types are essential for handling multi-valued fields, building lookup tables, and processing groups of records.
Lists
List Literals
Create a list using square brackets with comma-separated values:
[1, 2, 3, 4, 5]
['open', 'in_progress', 'resolved']
[True, False, True]
Lists can contain mixed types:
['incident', 42, True, None]
Indexing
Access individual elements by position (zero-based):
my_list[0]
Returns the first element.
my_list[-1]
Returns the last element.
my_list[2]
Returns the third element.
Slicing
Extract a portion of a list using slice notation:
my_list[1:3]
Returns elements at index 1 and 2 (the end index is exclusive).
my_list[:5]
Returns the first five elements.
my_list[2:]
Returns everything from index 2 onward.
my_list[::2]
Returns every other element (step of 2).
List Methods
Lists support a variety of methods for modification and querying:
| Method | Description | Example |
|---|---|---|
.append(item) |
Add an item to the end | my_list.append('new') |
.extend(items) |
Add all items from another iterable | my_list.extend([4, 5, 6]) |
.insert(i, item) |
Insert at a specific position | my_list.insert(0, 'first') |
.count(item) |
Count occurrences of an item | my_list.count('bug') |
.index(item) |
Find the index of the first occurrence | my_list.index('critical') |
.sort() |
Sort the list in place | my_list.sort() |
.reverse() |
Reverse the list in place | my_list.reverse() |
.pop() |
Remove and return the last item | my_list.pop() |
.remove(item) |
Remove the first occurrence of an item | my_list.remove('done') |
Dictionaries
Dictionary Literals
Create a dictionary using curly braces with key-value pairs:
{'key': 'value', 'status': 'active', 'priority': 1}
Keys are typically strings, and values can be any type:
{'name': 'John Doe', 'age': 30, 'active': True, 'tags': ['admin', 'user']}
Accessing Values
Use bracket notation to access a value by its key:
my_dict['status']
Returns the value associated with 'status'. Raises a KeyError if the key does not exist.
Use .get() for safe access with a default value:
my_dict.get('status', 'unknown')
Returns the value for 'status', or 'unknown' if the key is missing.
Dictionary Methods
| Method | Description | Example |
|---|---|---|
.get(k, d) |
Get value for key, or default if missing | my_dict.get('key', 'default') |
.keys() |
Return all keys | list(my_dict.keys()) |
.values() |
Return all values | list(my_dict.values()) |
.items() |
Return all key-value pairs | list(my_dict.items()) |
.pop(k) |
Remove and return value for key | my_dict.pop('old_key') |
.update(d2) |
Merge another dictionary into this one | my_dict.update({'new': 'val'}) |
Dictionary Lookup Pattern
A very common use of dictionaries in Precision Bridge is as lookup tables. For example, if you have an incident_id_map variable (a dictionary mapping old IDs to new IDs):
incident_id_map.get([sys_id], 'Not Found')
This looks up the current record's sys_id in the mapping and returns the new ID, or 'Not Found' if it does not exist.
Tuples
Tuples are similar to lists but are immutable (cannot be modified after creation):
(1, 2, 3)
('key', 'value')
Tuples support the same indexing and slicing syntax as lists:
my_tuple[0]
my_tuple[1:3]
Use tuples when you need an ordered collection that should not be changed.
Sets
Sets are unordered collections of unique values:
{1, 2, 3, 4, 5}
{'open', 'closed', 'pending'}
Sets automatically remove duplicates:
set([1, 1, 2, 2, 3])
Produces {1, 2, 3}.
Built-in Functions for Collections
Several built-in functions are particularly useful when working with collections:
| Function | Description | Example |
|---|---|---|
len() |
Return the number of items |
len([description]) -- character count |
min() |
Return the smallest item | min([score1], [score2], [score3]) |
max() |
Return the largest item | max(1, [priority], 3) |
sum() |
Sum all items in an iterable |
sum([10, 20, 30]) returns 60
|
sorted() |
Return a new sorted list |
sorted([3, 1, 2]) returns [1, 2, 3]
|
reversed() |
Return items in reverse order |
list(reversed([1, 2, 3])) returns [3, 2, 1]
|
enumerate() |
Pair each item with its index |
list(enumerate(['a', 'b'])) returns [(0, 'a'), (1, 'b')]
|
zip() |
Combine multiple iterables element-wise |
list(zip([1,2], ['a','b'])) returns [(1, 'a'), (2, 'b')]
|
range() |
Generate a sequence of integers |
list(range(5)) returns [0, 1, 2, 3, 4]
|
all() |
True if all items are truthy |
all([True, True, False]) returns False
|
any() |
True if any item is truthy |
any([False, False, True]) returns True
|
filter() |
Filter items by a condition |
list(filter(None, [0, 1, '', 'a'])) returns [1, 'a']
|
map() |
Apply a function to each item |
list(map(str, [1, 2, 3])) returns ['1', '2', '3']
|
Practical Examples
Get the first tag from a comma-separated string
[tags].split(',')[0].strip()
Splits the tags field by commas, takes the first element, and trims whitespace.
Count characters in a description
len(str([description])) if [description] is not None else 0
Returns the character count, handling the case where the field might be null.
Sort a list of values
sorted([priority_list])
Returns a new list with the items sorted in ascending order. Use sorted([priority_list], reverse=True) for descending order.
Dictionary lookup with a default
status_map.get([status], 'Unknown Status')
Looks up the source status value in a status_map dictionary variable, returning 'Unknown Status' if not found.
Check if a value exists in a list
[category] in ['hardware', 'software', 'network']
Returns True if the category field matches one of the listed values.
Next Steps
- Learn to generate collections dynamically with Comprehensions
- See all available built-in functions in Available Built-in Functions
Comments
0 comments
Please sign in to leave a comment.