Working with arrays and dictionaries

Array — is a data structure that stores a collection of values (called array elements), each identified by an index. It is defined using square brackets []. For example, the statement q = [] means that the variable q holds an empty array. If q = [2, 5, 7, 4, 9], then the array contains 5 elements — this is its length. The indices of the elements, which represent their positions in the array, start from 0. So, the index of the element "2" is 0, and the index of the element "4" in our array is 3.

Example: array=[1,2,3,4] or array1=["mother","father","son","daughter"]

An example of accessing an array element: array[1] (returns the value 2)

Dictionary — is a data structure that represents a specially organized set of elements which store data. All data is stored in the form of key-value pairs. Access to the data elements is performed using the key. A key always need to be unique within a single dictionary, while the data (values) can be duplicated if necessary.

Example: {"SLU":12345,"Name":"Men's t-shirt, white","Size":50,"Price":1000}

An example of accessing an array element: dictionary["Array"] (returns the value 12345)

Both arrays and dictionaries can have complex or nested structures — that is, they can contain one another. For example:

an array of dictionaries: products=[{"SKU":12345,"Name":"Men's t-shirt, white","Size":50,"Price":1000},{"SKU":12346,"Name":"Men's t-shirt, white","Size":52,"Price":1000}]

The expression s = {} means, that the variable s holds a dictionary that contains no elements.We can put a key-value pair in it, or even several: s = {"key1":"value1", "key2":"value2","key3":"value3"} Each key and value is enclosed in quotation marks, a colon is placed between the key and the value, and key-value pairs are separated by commas.

Arrays and dictionaries can be nested. Let’s look at an example:

rainbow = [red, orange, yellow, green, light blue, blue, purple] - this is an array.

If we write

rainbow = {"every":"red","hunter":"orange","wants":" yellow","know":"green","where":"light blue","sits":"blue","pheasant":"purple"}

- we get a dictionary

If we look closely at the rainbow, we can see, for example, that the light blue color is more complex and consists of turquoise, light blue, and dark blue. Let’s write: light blue = [turquoise,light blue, dark blue]. Now let’s embed our array “blue” into the dictionary “rainbow”:

rainbow = {"first_color":"red","second_color":"orange","third_color":"yellow","forth_color":"green","sixth_color":"blue","last_color":"purple"}

So how do we specify the address of an element, for example “turquoise”?

And in arrays, addressing is done by index, so the address of the element "turquoise" is 0.

Sum up this: ["where"][0] - is the address of the element "turquoise".

How to work with addressing (JSON)

When receiving responses from third-party services via API, we most often get JSON, which represents a dictionary. Quite often, we need to store a specific value from this dictionary into a variable.

The best way to understand the principle of addressing in JSON is through an example:{"suggestions": [{"value": "Dirham", "unrestricted_value": "Dirham", "data": {"code": "784", "strcode": "AED", "name": "Dirham", "country": "UAE"}}]}

Here we have a dictionary containing a single key-value pair suggestions - the key for the array: [{"value": "Dirham", "unrestricted_value": "Dirham", "data": {"code": "784", "strcode": "AED", "name": "Dirham", "country": "UAE"}}]

The value of the suggestions key is an array with only one element — a dictionary: {"value": "Dirham", "unrestricted_value": "Dirham", "data": {"code": "784", "strcode": "AED", "name": "Dirham", "country": "UAE"}} suggestions|0 - is the key to the first (and only) element of the array.{"value": "Dirham", "unrestricted_value": "Dirham", "data": {"code": "784", "strcode": "AED", "name": "Dirham", "country": "UAE"}}

suggestions|0|value - is the key to the value "Belarusian ruble"

{"suggestions": [{"value": "Dirham", "unrestricted_value": "Dirham", "data": {"code": "784", "strcode": "AED", "name": "Dirham", "country": "UAE"}}]}

The longest key path in this JSON is: suggestions|0|data|strcode - is the key for AED

{"suggestions": [{"value": "Dirham", "unrestricted_value": "Dirham", "data": {"code": "784", "strcode": "AED", "name": "Dirham", "country": "UAE"}}]}

Keys are separated by a vertical bar. If the JSON contains an array, access to its elements is done by index, starting from 0, and is also written using a vertical bar. Array indexing starts at 0.

In addressing, numbers are treated the same as strings and vice versa. For example, '6' and 6 are considered equal.

In addition to API responses, arrays and dictionaries can also be used to conveniently store data.

For example, if you need to restrict access to a specific section of a bot to certain users, you can store their IDs in an array, place it in a global project variable, and use it in block conditions or arrow logic to check whether the user’s ID is included in the array.

Another example is when you need to store, the number of points for each player in a team game. You can use a dictionary for this, where the keys are user IDs and the values are their points.

Sometimes, it is necessary to modify an array or a dictionary. The functions described in this article are designed for exactly that purpose. Most of the methods described below work with both arrays and dictionaries.

Working with arrays

How to create an array

Creating array - declaring an array

array_name = []

How to clear an array

Clearing an array is essentially the same as declaring an empty array:

array_name = []

How to access an array element

chevron-rightDescriptionhashtag

name[index] - accessing an array element by index or by value

chevron-rightExamplehashtag

Let's look at some examples of working with arrays:

Example of accessing an array element by its index:

Example of getting the last array element:

chevron-rightCode example to copyhashtag

How to replace a value in an array

chevron-rightDescriptionhashtag

name[index] = value - replacing an array element by a given index

chevron-rightExamplehashtag

Example:

To replace the value of a specific array element, use the following syntax: array_name[index] = value

Answer:

chevron-rightCode example to copyhashtag

How to check whether an element is in an array

chevron-rightDescriptionhashtag

in_array(mass, value) - to check if an element exists in an array.

Parameters: ! mass - array ! value - value for searching

Returns True or False depending on whether the value is found or not.

chevron-rightExamplehashtag

Example:

chevron-rightCode example to copyhashtag

How to find out array length

chevron-rightDescriptionhashtag

arr_len(mass) - to find out array length

Parameter: ! mass - array

Result: Returns number - array length.

circle-exclamation
chevron-rightExamplehashtag

Example of usage:

Result:

chevron-rightCode example to copyhashtag

How to insert an element at the end of an array?

chevron-rightDescriptionhashtag

append(mass, element, priznak) - to insert an element at the end of an array.

Parameters:

! mass - array ! element - element to insert priznak - flag indicating whether it’s an array or a dictionary

Returns the array with the value added at the end. To update the original array, use the assignment: mass = append(mass, element, priznak)

circle-exclamation
chevron-rightExamplehashtag

Example of usage:

Example of adding to and removing from an array:

In this example, an element is added to the project.vibpzdr array, and the value p is removed from the project.pzdr array

Example of creating an array with arrays inside:

The result of the function execution:

chevron-rightCode example to copyhashtag

How to insert a value at a specific position in an array

chevron-rightDescriptionhashtag

insert(mass, index, value, priznak) - to insert an element into a specific array position.

Parameters: ! mass - array ! index - insert position ! value - value indicator - Indicator of adding to an array or a dictionary.

Result: Returns an array with the value added at the specified position. In other words, to add the value to the same array, use the command in the following form: mass = insert(mass, index, value, indicator)

circle-exclamation
chevron-rightExamplehashtag

Example:

Result:

Let's look at a more complex example - adding a dictionary t to an array s:

In the function, we indicated that we want to add a dictionary to position 1. Let's look at the result:

chevron-rightCode example to copyhashtag

How to delete element from array

del() | del | remove()

chevron-rightDescriptionhashtag

By index

del(mass, key) - removes an element from the array by its index.

Parameters: ! mass - array name; ! key - the index of the value to be removed

Returns a new array with the element removed; the original array remains unchanged. To delete and update the same array, use the command like: mass = del(mass, key)

circle-exclamation

del name['index'] - removing a value from an array by index

Parameters: ! name- array name; ! index- the index of the value to be removed

By value

remove(mass, value) - to delete a value from an array.

Parameters: ! mass - array name; ! value - the value to remove from the array

Result: Returns a modified array, leaving the original array unchanged. To remove an element and update the same array, use the command in the following form: mass = remove(mass, key)

chevron-rightExampleshashtag

Example of removing an element by index:

Example of removing an array element by its value:

chevron-rightCode example to copyhashtag

How to get the position of an element in an array

chevron-rightDescriptionhashtag

index(mass, value)

Parameters: ! mass - array name ! value - the value whose position needs to be determined.

If the element is not in the array, the function will return -1.

chevron-rightExampleshashtag

Example of determining the position of an element in an array:

Let's take a closer look to the result in detail:

As we can see, since the number 5 is not in the array, the function returned -1.

chevron-rightCode example to copyhashtag

How to convert an array to human-readable text

chevron-rightDescriptionhashtag

massive_to_text(massive, header, numbered,delimiter1,delimiter2)

Parameters:

! massive – the array to be displayed, header – a title that will appear at the beginning of the output numbered – if any value is passed, the array elements will be numbered delimiter1 – the character placed at the end of each element line (default is ‘;’), delimiter2 – сthe character used after the item number when numbering is enabled (default is ‘)’)

chevron-rightExampleshashtag

Simple example:

As a result, the array will be displayed as a numbered list:

chevron-rightCode example to copyhashtag

How to exclude one array from another

chevron-rightDescriptionhashtag

except_arr(mas1, mas2)

Parameters:

! mas1 - the array from which elements will be excluded, ! mas2 - the array containing elements to be excluded

chevron-rightExampleshashtag

Let's look at the example:

chevron-rightCode example to copyhashtag

How to find the intersection of arrays

chevron-rightDescriptionhashtag

cross_arr(mas1, mas2)

Parameters:

! mas1 - the array to search in ! mas2 - the array containing elements to look for

chevron-rightExampleshashtag

chevron-rightCode example to copyhashtag

How to merge arrays

chevron-rightDescriptionhashtag

There is no built-in function specifically for merging arrays, but it can be easily done:

To combine arrays, perform string concatenation, then replace '][' with a comma ','

chevron-rightExampleshashtag

This is example in the Calculator field

This is example a bot working

chevron-rightCode example to copyhashtag

How to sum up the elements of an array

chevron-rightDescriptionhashtag

sum_array(array)

Parameters:

array - the array whose elements need to be summed

circle-exclamation
chevron-rightExampleshashtag

Result:

chevron-rightCode example to copyhashtag

How to shuffle the elements of an array

chevron-rightDescriptionhashtag

shuffle_massive(massive

Parameters:

massive - the array whose elements need to be shuffled.

chevron-rightExampleshashtag

Function execution results:

chevron-rightCode example to copyhashtag

For sorting arrays and dictionaries

sort() | sort_by_value()

chevron-rightDescriptionhashtag

Sorting in an array or a dictionary

sort(mass, b) - sorts an array by value, and a dictionary by key

Parameters:

! mass - array/dictionary b - sorting order (False – ascending (default), True – descending)

Sorting dictionary by its value

sort_by_value(dict, b) - sorts a dictionary by values.

Parameters: ! dict- dictionary b - sorting order (False – ascending (default), True – descending)

chevron-rightExamplehashtag

Example of sorting an array in descending order and a dictionary in ascending order:

sorting result

Sorting a dictionary by values:

sorting result

Converting an array/dictionary to buttons

tools_make_button_str_checker() | tools_check_user_input()

chevron-rightDescriptionhashtag

Converting an array/dictionary to buttons

tools_make_button_str_checker(values_list, key, in_line, button_type, checker_with_numbers)

Parameters:

! values_list - an array of strings or dictionaries whose data will be used to build a keyboard or a numbered list

key - the key by which selection will be made from an array of dictionaries

in_line - number of buttons per row (default: 1)

button_type - type of buttons (default: reply keyboard). Possible values: 0 - reply keyboard, 1 - iinline keyboard (buttons in text)

checker_with_numbers - whether to add button numbers to the "checker" array. Possible values: 0 - do not add numbers, 1 - add numbers (default: 1 – add numbers)

Function result — a dictionary of the form:

{"numbered_list":"1. T-shirts\n2. Shorts\n3. Socks\n4. Caps\n","buttons":[{"type":"inline","text":"T-shirts","line":0,"index_in_line":0},{"type":"inline","text":"Shorts","line":0,"index_in_line":1},{"type":"inline","text":"Socks","line":1,"index_in_line":0},{"type":"inline","text":"Caps","line":1,"index_in_line":1}],"checker":"T-shirts;1;Shorts;2;Socks;3;Caps;4;"}

The dictionary values can then be inserted into fields in the constructor:

Getting a dictionary value based on client selection

tools_check_user_input(values_list, user_input, key, return_key)

Parameters:

! values_list - an array of strings or dictionaries whose data will be used to build a keyboard or a numbered list Dictionary example: [{"text":"T-shirts","price":100},{"text":"Shorts","price":150},{"text":"Socks","price":20},{"text":"Caps","price":50}] ! user_input - the value entered by the user from one of the values in values_list Value example: Caps key - кthe key used for selection from the values_list array of dictionaries Key example: text return_key - the value returned for the specified key from values_list Return value example: price

chevron-rightExamplehashtag

Let’s break down the function usage with a shopping cart example:

1.Define an array and convert it into a numbered list, buttons, and a list of possible values (for messengers without buttons) using tools_make_button_str_checker() function.

Result of using tools_make_button_str_checker() function

2.Use the obtained buttons and numbered_list values to enable product selection:

3.Use the list of possible values checker to validate the client’s input:

4.Finally, display the price of the selected product to the client. This is convenient to do using the tools_check_user_input() function

chevron-rightCode example to copyhashtag

Data selection from an array

chevron-rightDescriptionhashtag

array_slice(array, start_index, end_index)

Parameters:

! array - array ! start_index - start of the slice end_index - end of the slice (default: until the end)

chevron-rightExamplehashtag

Let’s select a subarray starting from the 1st element:

Example of using array_slice()

res will be ["Shorts", "Socks", "Caps"]

Another example of selecting a subarray from the 0th to the 2nd element of the array:

Example of using array_slice()

res will be ["T-shirts", "Shorts"]

chevron-rightCode example to copyhashtag

Unpacking array elements

chevron-rightFunctionhashtag

unpack_list(array, var_name) - this method iterates over an array and creates a separate variable for each element in the array with names like var1, var2, var3 and ect.

! array - required parameter, an array of elements

var_name - optional parameter, a string. If provided, it is used for naming the unpacked elements. Examples:

If var_name is provided, the variable names are formed using var_name

var_name must follow variable naming rules.

chevron-rightExamplehashtag

Example 1:

array1 = ["one", "two", "three"]

ans1 = unpack_list(array1)

Result - created deal variables:

var1 = 'one'

var2 = 'two'

var3 = 'three'

Example 2:

array2 = ["one", "two", "three"]

var_name = 'custom'

ans2 = unpack_list(array2, var_name)

Result - created deal variables:

custom1 = 'one'

custom2 = 'two'

custom3 = 'three'

How to return a list without duplicate elements

chevron-rightDescriptionhashtag

remove_duplicates(array) - returns a list without duplicate elements.

! array - required parameter. The original list of elements with duplicates.

chevron-rightExamplehashtag

Example:

arr = [1, 2, 5, 1, 5, 3]

new_arr = remove_duplicates(arr)

Result - the list [1, 2, 5, 3] will be assigned to the variable new_arr.

How to create dictionary

chevron-rightDescriptionhashtag

Creating dictionary - declaring a dictionary

name_dictionary = {}

How to clear a dictionary

chevron-rightDescriptionhashtag

Сlearing - is nothing more than declaring an empty dictionary.

name_dictionary = {}

How to get the dictionary value by key

chevron-rightDescriptionhashtag

name[key] - getting a dictionary element by key

chevron-rightExampleshashtag

Example of working with a dictionary:

In this specific case, we’re accessing the value by the key "a". To retrieve a value from a dictionary using a specific key, use the following format: name_dictionary["key"]

Answer:

chevron-rightCode example to copyhashtag

How to get a list of keys from a dictionary

chevron-rightDescriptionhashtag

dict_keys_to_array(data) - to get a list of data dictionary keys

chevron-rightExampleshashtag

Example: Get a list of all dictionary keys

Answer:

chevron-rightCode example to copyhashtag

How to get a list of values from a dictionary

chevron-rightDescriptionhashtag

dict_values_to_array(data) - to get a list of values from a dictionary

chevron-rightExampleshashtag

Example:

Answer:

chevron-rightCode example to copyhashtag

How to get the values from the dictionary list by the specified key

chevron-rightDescriptionhashtag

get_values_by_key(data, key) - allows you to get values from the dictionary list by the specified key. Returns a list of values.

chevron-rightExamplehashtag

Example: Get values from a list of dictionaries by key

Answer:

chevron-rightCode example to copyhashtag

How to replace a value in a dictionary

chevron-rightDescriptionhashtag

name['key'] = value - replacing the dictionary element value by the specified key. If a non-existent key is specified, a new dictionary element will be added.

chevron-rightDescriptionhashtag

Example:

To replace the value of a specific array element, write an assignment like array_name[index] = value or dictionary_name[key] = value

Answer:

chevron-rightCode example to copyhashtag

How to add a value to a dictionary

chevron-rightDescriptionhashtag

dictionary_name['key'] = 'value' - adding a new value to the dictionary.

circle-exclamation
chevron-rightExamplehashtag

This is example the code in calculator field

Answer

chevron-rightCode example to copyhashtag

How to check if a key exists in a dictionary

chevron-rightDescriptionhashtag

exist_key(mass, key) - to check if a key exists in a dictionary.

Parameters:

mass - dictionary

key - the key to search for

Returns True or False depending on whether the key was found.

chevron-rightExamplehashtag

Example of usage:

chevron-rightCode example to copyhashtag

How to check the position of a key in a dictionary

chevron-rightDescriptionhashtag

key_index(mass, key) - to check the position of a key in a dictionary.

Parameters: mass - dictionary key - Key to search for.

circle-info

The position in a dictionary is counted from 0. Thus, the first element is 0, the second element is 1, and so on.

chevron-rightExamplehashtag

Example of usage:

Result:

chevron-rightCode example to copyhashtag

How to get the number of elements in a dictionary

chevron-rightDescriptionhashtag

arr_len(mass) - to determine the length of a dictionary.

Parameter: mass - dictionary

Result: Returns a number – the length of the dictionary.

circle-exclamation
chevron-rightExamplehashtag

Example of usage:

Answer:

How to delete an element from a dictionary

chevron-rightDescriptionhashtag

By index or key

del(mass, key) - to delete an element from a list by index or from a dictionary by key. It takes two parameters: the list/dictionary and the index/key to delete. Returns the modified dictionary or list without changing the original object.

circle-exclamation
chevron-rightExamplehashtag

Example with a dictionary

Result

Example with an array

Result

chevron-rightCode example to copyhashtag

Example with a dictionary

s={"1":123, "2":234, "q":{"w":"e"}}

q=del(s,'q')

Example with an array

s=["John", "Ann", "Sophie"]

q=del(s, 1)

How to convert a dictionary into a human-readable text

chevron-rightDescriptionhashtag

humanize(dict, delimiter, from_i, to_i)

Parameters:

dict - dictionary name delimiter - delimiter between lines from_i - index of the element to start output from (0-based) to_i - index of the element to end output at (not inclusive)

chevron-rightExamplehashtag

Let's look at the example:

Answer

chevron-rightCode example to copyhashtag

For sorting dictionaries

sort() | sort_by_value()

chevron-rightDescriptionhashtag

Dictionary sorting

sort(dict, b) - Sorts a list by value, and a dictionary by key

Parameters:

! dict- dictionary

b - sorting direction (False – ascending by default, True – descending)

Dictionary sorting by value

sort_by_value(dict, b) - Sorting a dictionary by values.

Parameters:

! dict- dictionary

b - sorting direction (False – ascending by default, True – descending)

chevron-rightExampleshashtag

Example: sorting a list in descending order and a dictionary in ascending order:

Sorting a dictionary by its values:

chevron-rightCode example to copyhashtag

Example: sorting a list in descending order and a dictionary in ascending order:

array1=[5,4,0,6,3,0]

array1=sort(array1, True)

dict={"Ann":5, "John":4, "Sophie":0, "Alex":6, "Kate":3, "Harry":0}

dict=sort(dict)

Sorting a dictionary by its values:

dict={"Ann":5, "John":4, "Sophie":0, "Alex":6, "Kate":3, "Harry":0}

dict=sort_by_value(dict)

Last updated