ScriptForge.Dictionary service

A dictionary is a collection of key-item pairs

Keys and items can be retrieved, counted, updated, and much more.

Tip Icon

LibreOffice Basic Collection object does not support the retrieval of the keys.
Additionally its items contain only primitive Basic data types such as dates, text, numbers, and the like.


Service invocation

The following example creates myDict as an empty dictionary.


    GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
    Dim myDict As Variant
    myDict = CreateScriptService("Dictionary")
  

It is recommended to free resources after use:


     Set myDict = myDict.Dispose()
  

Properties

Name

Read-only

Type

Description

Count

Yes

Long

The number of entries in the dictionary

Items

Yes

Array of Variants

The list of items as a one dimensional array

Keys

Yes

Array of Strings

The list of keys as a one dimensional array


Tip Icon

The Keys and Items properties return their respective contents, using an identical ordering. The order is unrelated to the creation sequence.


Example:

The following example uses the Keys property to iterate over all keys in the dictionary myDict.


    Dim a As Variant, b As String
    a = myDict.Keys
    For Each b In a
        MsgBox(myDict.Item(b))
    Next b
    

Methods

Add
ConvertToArray
ConvertToJson
ConvertToPropertyValues

Exists
ImportFromJson
ImportFromPropertyValues
Item

Remove
RemoveAll
ReplaceItem
ReplaceKey


Add

Adds a new key-item pair into the dictionary. Returns True if successful.

Syntax:


          myDict.Add(Key As String, Item As Variant) As Boolean
        

Parameters:

Key : String value used to identify the Item. The key is not case-sensitive.

Item : Any value, including an array, a Basic object, a UNO object, a dictionary, etc.

Example:


          Dim NewValue As Variant
          myDict.Add("NewKey", NewValue)
       
warning

Every key must be unique in the same dictionary. If the key already exists in the dictionary, a DUPLICATEKEYERROR will be raised. Keys that are made of space characters will raise a INVALIDKEYERROR error.


ConvertToArray

Stores the contents of the dictionary in a two-columns zero-based array. The keys are stored in the first column and the items are stored in the second column.

If the dictionary is empty, this method will return an empty Array.

Syntax:


          myDict.ConvertToArray() As Variant
        

Example:


        Dim myDict as Variant
        myDict = CreateScriptService("Dictionary")
        myDict.Add("a", 1)
        myDict.Add("b", 2)
        myDict.Add("c", 3)
        Dim arr as Variant
        arr = myDict.ConvertToArray()
        '(("a", 1), ("b", 2), ("c", 3))
      

ConvertToJson

Converts the contents of a dictionary to JSON (JavaScript Object Notation) text.

Limitations

This method supports the following data types: String, Boolean, numbers, Null and Empty. Arrays containing items of those types are also allowed, whatever their dimensions. Dates are converted into strings, however they cannot be used inside Arrays. Other data types are converted to their string representation using the SF_String.Represent service.

Syntax:


            myDict.ConvertToJson([Indent As Variant]) As String
        

Parameters:

Indent : When Indent is a positive number or a text, JSON array elements and object members are pretty-printed with that indentation level. A negative Indent value will add new lines with no indentation. Indent default value "" selects the most compact representation. Using a positive integer for Indent indents that many spaces per level. When Indent is a string, such as Chr(9) or Tab(1), the Tab character is used to indent each level.

Example:


            myDict.Add("p0", 12.5)
            myDict.Add("p1", "a string àé""ê")
            myDict.Add("p2", DateSerial(2020,9,28))
            myDict.Add("p3", True)
            myDict.Add("p4", Array(1,2,3))
            MsgBox myDict.ConvertToJson()    
            '{"p0": 12.5, "p1": "a string \u00e0\u00e9\"\u00ea", "p2": "2020-09-28", "p3": true, "p4": [1, 2, 3]}
        

ConvertToPropertyValues

Store the content of the dictionary in an array of PropertyValues.

Each entry in the array is a com.sun.star.beans.PropertyValue. The key is stored in Name, the item is stored in Value.

If one of the items has a type Date, it is converted to a com.sun.star.util.DateTime structure. If one of the items is an empty array, it is converted to Null. The resulting array is empty when the dictionary is empty.

Syntax:


          myDict.ConvertToPropertyValues() As Variant
        

Example:


          Dim myDict as Variant
          myDict = CreateScriptService("Dictionary")
          'Adds some properties to the dictionary
          myDict.Add("Color", "Blue")
          myDict.Add("Width", 20)
          'Converts to an Array of PropertyValue objects
          Dim prop as Variant
          prop = myDict.ConvertToPropertyValues()
        
tip

Many services and methods in the UNO library take in parameters represented using the PropertyValue struct, which is part of the LibreOffice API.


Exists

Determines if a key exists in the dictionary.

Syntax:


          myDict.Exists(Key As String) As Boolean
        

Parameters:

Key : The key to be looked up in the dictionary.

Example:


          Dim myDict as Variant
          myDict = CreateScriptService("Dictionary")
          'Adds some properties to the dictionary
          myDict.Add("Color", "Blue")
          myDict.Add("Width", 20)
          '(...)
          If Not myDict.Exists("Size") Then
             MsgBox "You have to provide a Size value"
          End If
        

ImportFromJson

Adds the content of a JSON (JavaScript Object Notation) string into the current dictionary. Returns True if successful.

Limitations

The JSON string may contain numbers, text, booleans, null values and arrays containing those types. It must not contain JSON objects namely sub-dictionaries.

An attempt is made to convert text to date if the item matches one of these patterns: YYYY-MM-DD, HH:MM:SS or YYYY-MM-DD HH:MM:SS.

Syntax:


            myDict.ImportFromJson(InputStr As String, [Overwrite As Boolean]) As Boolean
        

Parameters:

InputStr : The string to import.

Overwrite : When True, entries with same name may exist in the dictionary and their values are overwritten. When False (default), repeated keys will raise an error. Beware that dictionary keys are not case-sensitive while names are case-sensitive in JSON strings.

Example:


            Dim s As String
            s = "{'firstName': 'John','lastName': 'Smith','isAlive': true,'age': 66, 'birth':  '1954-09-28 20:15:00'" _
                & ",'address': {'streetAddress': '21 2nd Street','city': 'New York','state': 'NY','postalCode': '10021-3100'}" _
                & ",'phoneNumbers': [{'type': 'home','number': '212 555-1234'},{'type': 'office','number': '646 555-4567'}]" _
                & ",'children': ['Q','M','G','T'],'spouse': null}"
            s = Replace(s, "'", """")
            myDict.ImportFromJson(s, OverWrite := True)
            'The (sub)-dictionaries "address" and "phoneNumbers" (0) and (1) are imported as Empty values.
        

ImportFromPropertyValues

Inserts the contents of an array of PropertyValue objects into the current dictionary. PropertyValue Names are used as Keys in the dictionary, whereas Values contain the corresponding values. Returns True if successful.

Syntax:


            myDict.ImportFromPropertyValues(PropertyValues As Variant [, Overwrite As Boolean]) As Boolean
        

Parameters:

PropertyValues : A zero-based 1 dimensional array containing com.sun.star.beans.PropertyValue objects. This parameter may also be a single PropertyValue object not contained in an Array.

Overwrite : When True, entries with same name may exist in the dictionary and their values are overwritten. When False (default), repeated keys will raise an error. Note that dictionary keys are not case-sensitive, whereas names are case-sensitive in sets of property values.

Example:


            Dim vProp As New com.sun.star.beans.PropertyValue
            vProp.Name = "prop"
            vProp.Value = CDateToUnoDateTime(Now)
            myDict.ImportFromPropertyValues(vProp, Overwrite := True)
        

Item

Retrieves an existing dictionary entry based on its key. Returns the value of the item if successful, otherwise returns Empty.

Syntax:


          myDict.Item(Key As String) As Variant
        

Parameters:

Key : Not case-sensitive. Must exist in the dictionary, otherwise a UNKNOWNKEYERROR error is raised.

Example:

The following example iterates over all keys in the dictionary and uses the Item method to access their values.


          Dim myDict as Variant, k as Variant, allKeys as Variant
          myDict = CreateScriptService("Dictionary")
          myDict.Add("key1", 100)
          myDict.Add("key2", 200)
          myDict.Add("key3", 300)
          allKeys = myDict.Keys
          For Each k in allKeys
             MsgBox(myDict.Item(k))
          Next k
       

Remove

Removes an existing dictionary entry based on its key. Returns True if successful.

Syntax:


          myDict.Remove(Key As String) As Boolean
        

Parameters:

Key : Not case-sensitive. Must exist in the dictionary, otherwise an UNKNOWNKEYERROR error is raised.

Example:


          myDict.Add("key1", 100)
          myDict.Add("key2", 200)
          myDict.Add("key3", 300)
          MsgBox(myDict.Count) 'Prints "3"
          myDict.Remove("key2")
          MsgBox(myDict.Count) 'Prints "2"
       

RemoveAll

Removes all the entries from the dictionary. Returns True if successful.

Syntax:


          myDict.RemoveAll() As Boolean
        

Example:


          myDict.Add("key1", 100)
          myDict.Add("key2", 200)
          myDict.Add("key3", 300)
          MsgBox(myDict.Count) 'Prints "3"
          myDict.RemoveAll()
          MsgBox(myDict.Count) 'Prints "0"
        

ReplaceItem

Replaces an existing item value based on its key. Returns True if successful.

Syntax:


          myDict.ReplaceItem(Key As String, Value As Variant) As Boolean
        

Parameters:

Key : String value representing the key whose value will be replaced. Not case-sensitive. If the key does not exist in the dictionary, a UNKNOWNKEYERROR error is raised.

Value : The new value of the item referred to with the Key parameter.

Example:


          myDict.Add("a", 1)
          MsgBox(myDict.Item("a")) 'Prints "1"
          myDict.ReplaceItem("a", 100)
          MsgBox(myDict.Item("a")) ' Prints "100"
       

ReplaceKey

Replaces an existing key in the dictionary by a new key. The item value is left unchanged. Returns True if successful.

Syntax:


          myDict.ReplaceKey(Key As String, Value As String) As Boolean
        

Parameters:

Key : String value representing the key to be replaced. Not case-sensitive. If the key does not exist in the dictionary, a UNKNOWNKEYERROR error is raised.

Value : String value for the new key. Not case-sensitive. If the new key already exists in the dictionary, a DUPLICATEKEYERROR error is raised.

Example:


          myDict.Add("oldKey", 100)
          MsgBox(myDict.Item("oldKey")) 'Prints "100"
          myDict.ReplaceKey("oldKey", "newKey")
          MsgBox(myDict.Item("newKey")) ' Prints "100"
       
warning

All ScriptForge Basic routines or identifiers that are prefixed with an underscore character "_" are reserved for internal use. They are not meant be used in Basic macros.


Please support us!