ScriptForge.Dictionary zerbitzua

Hiztegi bat gako-elementu bikoteen bilduma bat da

Gakoak eta elementuak atzitu, zenbatu eta eguneratu daitezke, eta beste hainbat ekintza gauzatu daitezke haiekin.

Iradokizun-ikonoa

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 object or JSON string.


Zerbitzuari deitzea

Basic lengoaian

Hurrengo adibideak myDict izeneko hiztegi hutsa sortzen du.


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

Gomendagarria da baliabideak askatzea haiek erabili ondoren:


     Set myDict = myDict.Dispose()
  
Python lengoaian

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 dict 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)
    # Initialize myDict with the content of dico
    myDict = CreateScriptService('Dictionary', dico)
    myDict['D'] = 4
    print(myDict) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}
    propval = myDict.ConvertToPropertyValues()
  
note

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


Propietateak

Izena

Irakurtzeko soilik

Mota

Deskribapena

Count

Bai

Long

Hiztegiaren sarrera kopurua

Items

Bai

Aldagaien matrizea

Elementu kopurua dimentsio bakarreko matrize gisa

Keys

Bai

Kate-matrizea

Gakoen zerrenda dimentsio bakarreko matrize gisa


Iradokizun-ikonoa

Keys eta Items propietateek bakoitzak bere edukiak itzultzen dituzte, ordena berdina erabilita. Ordenak ez du zerikusirik sorrera-sekuentziarekin.


Adibidea:

Hurrengo adibideak Keys propietatea darabil myDict hiztegiko gako guztietan iteratzeko.


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

Metodoak

Add
ConvertToArray
ConvertToJson
ConvertToPropertyValues

Exists
ImportFromJson
ImportFromPropertyValues
Item

Remove
RemoveAll
ReplaceItem
ReplaceKey


Add

Gako-elementu bikote berria gehitzen dio hiztegiari. True itzultzen du eragiketa ongi gauzatzen bada.

Sintaxia:

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

Parametroak:

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.

Adibidea:


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

Gako bakoitzak bakarra izan behar du hiztegi berean. Gakoa lehendik badago hiztegian, DUPLICATEKEYERROR errore bat sortuko da. Zuriuneekin egindako gakoek INVALIDKEYERROR errorea sortuko dute.


ConvertToArray

Hiztegiaren edukiak zeron oinarritutako bi zutabeko matrize baten biltegiratzen ditu. Gakoak lehen zutabean biltegiratuko dira eta elementuak bigarren zutabean.

Hiztegia hutsik badago, metodo honek hutsik dagoen Array bat itzuliko du.

Sintaxia:

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

Adibidea:


      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

Hiztegi bateko edukiak JSON (JavaScript Object Notation) testu bihurtzen ditu.

Mugak

Metodo honek honako datu motak onartzen ditu: String, Boolean, zenbakiak, Null eta Empty. Mota horretako elementuak dituzten matrizeak ere onartzen dira, berdin dio haien dimentsioak zein diren. Datak kate bihurtzen dira, baina ezin dira matrizeen barruan erabili. Beste datu motak kate modura duten ordezkapenera bihurtzen dira, SF_String.Represent zerbitzuaren bidez.

Sintaxia:

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

Parametroak:

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.

Adibidea:


      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.

Matrizeko sarrera bakoitza com.sun.star.beans.PropertyValue bat da. Gakoa Name aldean biltegiratzen da, eta elementua Value aldean.

Elementuren bat Date motakoa bada, com.sun.star.util.DateTime egitura bihurtuko da. Elementuren bat matrize huts bat bada, Null bihurtuko da. Emaitza gisa sortutako matrizea hutsik egongo da hiztegia hutsik badago.

Sintaxia:

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

Adibidea:

Basic lengoaian

    Dim myDict as Variant
    myDict = CreateScriptService("Dictionary")
    'Zenbait propietate gehitzen dizkio hiztegiari
    myDict.Add("Color", "Blue")
    myDict.Add("Width", 20)
    'PropertyValue objektuen matrize bihurtzen du
    Dim prop as Variant
    prop = myDict.ConvertToPropertyValues()
  
Python lengoaian

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

UNO liburutegiko zerbitzu eta metodo askok PropertyValue egitura erabilita adierazten diren parametroak dituzte. Egitura hori LibreOffice APIkoa da.


Exists

Gako bat hiztegian badagoen ala ez zehazten du.

Sintaxia:

dict.Exists(key: str): bool

Parametroak:

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

Adibidea:


    Dim myDict as Variant
    myDict = CreateScriptService("Dictionary")
    'Zenbait propietate gehitzen dizkio hiztegiari
    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

JSON (JavaScript Object Notation) kate bateko edukia uneko hiztegiari gehitzen dio. True itzultzen du ongi gauzatzen bada.

Mugak

JSON kateak eduki ditzake zenbakiak, testua, boolearrak, balio nuluak eta mota horiek dituzten matrizeak. Ez ditu eduki behar azpihiztegi deituriko JSON objektuak.

Testua data bihurtzeko saiakera egiten da elementuak honako ereduetako bat badu: UUUU-HH-EE, OO:MM:SS edo UUUU-HH-EE OO:MM:SS.

Sintaxia:

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

Parametroak:

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.

Adibidea:


    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)
    ' "address" eta "phoneNumbers" (0) eta (1) azpi-hiztegiak balio huts gisa inportatuko dira.
  

ImportFromPropertyValues

PropertyValue objektuen matrize baten balioak uneko hiztegian txertatzen ditu. PropertyValue izenak gako modura erabiltzen dira hiztegian, eta balioak balio gisa. True itzultzen du eragiketa ongi gauzatu bada.

Sintaxia:

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

Parametroak:

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.

Adibidea:

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

Basic lengoaian

    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
  
Python lengoaian

    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

Hiztegi batean dagoen sarrera bat atzitzen du, bere gakoa erabilita. Elementuaren balioa itzultzen du eragiketa ongi gauzatu bada, bestela Empty itzultzen du.

Sintaxia:

dict.Item(key: str): any

Parametroak:

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

Adibidea:

Hurrengo adibidean, hiztegiko gako guztien iterazio bat egiten da eta Item metodoa erabiltzen da beren balioak atzitzeko.


    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

Hiztegiko sarrera bat kentzen du bere gakoan oinarrituta. True itzultzen du eragiketa ongi gauzatzen bada.

Sintaxia:

dict.Remove(key: str): bool

Parametroak:

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

Adibidea:


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

RemoveAll

Hiztegiko sarrera guztiak kentzen ditu. True (egia) itzultzen du ongi gauzatzen bada.

Sintaxia:

dict.RemoveAll(): bool

Adibidea:


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

ReplaceItem

Elementu-balio bat ordezten du bere gakoan oinarrituta. True (egia) itzultzen du ongi gauzatzen bada.

Sintaxia:

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

Parametroak:

key: String value representing the key whose value will be replaced. Not case-sensitive. 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.

Adibidea:


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

ReplaceKey

Hiztegiko gako bat beste gako batekin ordezten du. Elementuaren balioa ez da aldatuko. True itzultzen du eragiteka ongi gauzatzen bada.

Sintaxia:

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

Parametroak:

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, an DUPLICATEKEYERROR error is raised.

Adibidea:


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

Azpimarraren karaktere bat, "_", aurrizki gisa duten ScriptForge Basic errutina edo identifikatzaile guztiak barneko erabilerarako erreserbatuta daude. Ez dira Basic makroetan edo Python scriptetan erabili behar.