Servei ScriptForge.Dictionary

Contingut

# ScriptForge.Dictionary service

A dictionary is a collection of key-item pairs

- The key is a string. In Basic scripts, the case sensitivity of the key is determined at Dictionary creation. In Python scripts, the key is always case-sensitive.

- Els elements poden ser de qualsevol tipus

Les claus i els elements es poden recuperar, comptar, actualitzar i molt més.

The Dictionary service is similar to the built-in LibreOffice Basic Collection object, however with more features. For example, Collection objects do not support the retrieval of keys. Moreover, Dictionaries provide additional capabilities as replacing keys, testing if a specific key already exists and converting the Dictionary into an array of PropertyValues or a JSON string.

## Invocació del servei

##### En Basic

The following example creates myDict as an empty dictionary.

        GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
        Dim myDict As Variant
        myDict = CreateScriptService("Dictionary", True)
                    ' The keys are case-sensitive, hence the second argument is True

Es recomana alliberar els recursos després de l'ús:

         Set myDict = myDict.Dispose()

##### En Python

The example below creates an empty instance of the Dictionary service and uses the Python native update method to populate it with the contents of a Python dict object.

        dico = dict('A' = 1, 'B' = 2, 'C' = 3)
        # Initialize myDict as an empty Dictionary object
        myDict = CreateScriptService('Dictionary')
        # Load the values of dico into myDict
        myDict.update(dico)
        myDict['D'] = 4
        print(myDict)   # {'A': 1, 'B': 2, 'C': 3, 'D': 4}
        propval = myDict.ConvertToPropertyValues()

It is possible to create an instance of the Dictionary service using a Python dict object as argument as shown in the following example.

        dico = dict('A' = 1, 'B' = 2, 'C' = 3)
        # Inicialitza myDict amb el contingut de dico
        myDict = CreateScriptService('Dictionary', dico)
        myDict['D'] = 4
        print(myDict) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}
        propval = myDict.ConvertToPropertyValues()

Because Python has built-in dictionary support, most of the methods in the Dictionary service are available for Basic scripts only. Exceptions are the ConvertToPropertyValues and ImportFromPropertyValues methods that are supported in both Basic and Python.

## Propietats

Nom | Només de lectura | Tipus | Descripció
--- | --- | --- | ---
Count | Sí | Long | El nombre d'entrades al diccionari
Items | Sí | Matriu de variants | The list of items as a one dimensional array
Keys | Sí | Matriu de cadenes | The list of keys as a one dimensional array

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

### Exemple:

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

Llista de mètodes del servei Dictionary
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.

### Sintaxi:

dict.Add(key: str, item: any): bool

### Paràmetres:

key: String value used to identify the Item. The case sensitivity of the key was determined at Dictionary creation..

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

### Exemple:

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

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.

### Sintaxi:

dict.ConvertToArray(): any[0..*, 0..1]

### Exemple:

          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.

### Limitacions

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.

### Sintaxi:

dict.ConvertToJson(indent: str = ""): str

### Paràmetres:

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. The default value is an empty string "" which 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.

### Exemple:

          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

Stores the contents of the dictionary into 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.

### Sintaxi:

dict.ConvertToPropertyValues(): obj[0..*]

### Exemple:

##### En Basic

        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()

##### En Python

Note in the example below that a Python dictionary needs to be passed as the second argument of the CreateScriptService method.

        myDict = dict()
        myDict["Color"] = "Blue"
        myDict["Width"] = 30
        sfDic = CreateScriptService("Dictionary", myDict)
        prop = sfDic.ConvertToPropertyValues()

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.

### Sintaxi:

dict.Exists(key: str): bool

### Paràmetres:

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

### Exemple:

        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.

### Limitacions

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.

### Sintaxi:

dict.ImportFromJson(inputstr: str, overwrite: bool = False): bool

### Paràmetres:

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. Be aware that dictionary keys are not case-sensitive while names are case-sensitive in JSON strings.

### Exemple:

        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.

### Sintaxi:

dict.ImportFromPropertyValues(propertyvalues: obj[0..*], overwrite: bool = False): bool

### Paràmetres:

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 in Basic, whereas names are case-sensitive in sets of property values and in Python dictionaries.

### Exemple:

The examples below first create an array with two PropertyValue objects and then convert it to a dictionary.

##### En Basic

        Dim vProp As New com.sun.star.beans.PropertyValue
        Dim arrProp : arrProp = Array()
        vProp.Name = "Color"
        vProp.Value = "Blue"
        arrProp = SF_Array.Append(arrProp, vProp)
        vProp.Name = "Date"
        vProp.Value = CDateToUnoDateTime(Now)
        arrProp = SF_Array.Append(arrProp, vProp)
        myDict = CreateScriptService("Dictionary")
        myDict.ImportFromPropertyValues(arrProp, Overwrite := True)
        Dim keys : keys = myDict.Keys
        For Each k In keys
            MsgBox k & " - " & myDict.Item(k)
        Next k

##### En Python

        from scriptforge import CreateScriptService
        from datetime import datetime
        import uno
        bas = CreateScriptService("Basic")
        arrProp = list()
        vProp = uno.createUnoStruct("com.sun.star.beans.PropertyValue")
        vProp.Name = "Color"
        vProp.Value = "Blue"
        arrProp.append(vProp)
        vProp = uno.createUnoStruct("com.sun.star.beans.PropertyValue")
        vProp.Name = "Date"
        vProp.Value = bas.CDateToUnoDateTime(datetime.now())
        arrProp.append(vProp)
        myDict = CreateScriptService("Dictionary")
        myDict.ImportFromPropertyValues(arrProp, overwrite=True)
        for k in myDict.keys():
            bas.MsgBox("{} - {}".format(k, myDict[k]))

## Item

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

### Sintaxi:

dict.Item(key: str): any

### Paràmetres:

key: If it does not exist, the Empty value is returned.

### Exemple:

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.

### Sintaxi:

dict.Remove(key: str): bool

### Paràmetres:

key: Must exist in the dictionary, otherwise an UNKNOWNKEYERROR error is raised.

### Exemple:

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

## RemoveAll

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

### Sintaxi:

dict.RemoveAll(): bool

### Exemple:

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

## ReplaceItem

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

### Sintaxi:

dict.ReplaceItem(key: str, value: any): bool

### Paràmetres:

key: String value representing the key whose value will be replaced. If the key does not exist in the dictionary, an UNKNOWNKEYERROR error is raised.

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

### Exemple:

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

## ReplaceKey

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

### Sintaxi:

dict.ReplaceKey(key: str, value: str): bool

### Paràmetres:

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

value: String value for the new key. If the new key already exists in the dictionary, a DUPLICATEKEYERROR error is raised.

### Exemple:

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

Totes les rutines o identificadors bàsics de ScriptForge que tenen el prefix de guió baix "_" estan reservats per a ús intern. No estan pensats per utilitzar-los en macros de Basic o scripts de Python.

Temes relacionats

Servei ScriptForge.Array

Collection Object

Ens cal la vostra ajuda!