I am trying to connect to a payment API service, it require me to make a dictionary then make it a long string then send it to them, I have made the dictionary but can not find a way to loop through this Dictionary to make it a string, please is there a way I can use FOR NEXT to loop through a Dictionary.
Here is how I am trying to do:
First, make a dictionary:
DIM dict AS DICTIONARY
dict.value("orderNumber")="1234"
dict.value("orderAmount")="200"
dict.value("paymentMethod")="creditCard"
and more ...
Second, I need to make it a String:
DIM str AS STRING
str = str + "HashKey=5294y06JbISpM5x9"
str = str + "&orderNumber=1234"
str = str + "&orderAmount=200"
str = str + "&paymentMethod=creditCard"
and more ...
str = str + "&HashIV=v77hoKGq4kWxNNIS"
If there is a way I can loop through this dictionary, maybe I can make my code like this?
FOR dict = 0 TO dict.count -1
str = str + "&" + dict(0).hash + "=" + dict(0).value
NEXT
Use the Keys property of the Dictionary, which is an array of the Dictionary’s keys:
Dim dict As New Dictionary
FOR Each key As Variant In dict.Keys
str = str + "&" + key + "=" + dict.Value(key)
NEXT
See also Dictionary.Values, which is an array of the Dictionary’s values in the same order as the Keys array.
And the keys might be sorted?
The order is unspecified, but will be consistent until an item is added or removed.
I wish our dictionary class had a flag that could be set to return keys in the order of insertion or sorted.
I think this ‘indeterminate’ order is going to bite a lot of peoples ‘code’.
[quote=192358:@Brian O’Brien] Dim dict As New Dictionary
FOR Each key As Variant In dict.Keys
str = str + “&” + key + “=” + dict.Value(key)
NEXT[/quote]
From what I see, the method lists the keys in the order they were created.
To sort them by key name is extremely simple :
FOR Each key As Variant In dict.Keys
myArray.Append(key + "=" + dict.Value(key))
NEXT
myArray.sort
msgbox join(myarray,EndOfLine)
Sorting by key value is much more involved and sometimes impossible, as it can be any type or object.