Blockly Dictionary Loop

I have created a Blockly Dictionary. But I was not able to loop over it e.g. with “count with … do” or “for each item in list”.

Also “length of” is not working for the dictionary and in the blockly documentation is no example for a loop and a dictionary.

Has anyone experience with dictionaries and blockly?

This works for me

Is this what you intend to do?

Ok. I guess num represents the value and not the key. Is it also possible to access the key with this apporach? I need the key and the value in the loop.

There is a solution that isn’t that elegant but before I come to that, let me explain what is happening here. The blocks generate the following code

myMap = {'key0': 'one', 'key1': 'two', 'key2': 'three'};
for (var num_index in myMap) {
  num = myMap[num_index];;

So, you can see, it is actually iterating via an index because it perceives it as a index as usually it would use a list-array. However it works, because in that case the index is the key and it is used to lookup the value in the map.

Let’s rename the variable to key and magically the block will create a code that generates a key and a key_index variable

and this code

myMap = {'key0': 'one', 'key1': 'two', 'key2': 'three'};
for (var key_index in myMap) {
  key = myMap[key_index];'myMap[key_index] =' + String(key)));

So the key(index) is actually there but you just can’t access it via a block, right?

well, there is a way of doing it with a trick:

  • define a variable myIndex
  • use a script block to assign the variable key_index to it.

Of course, this is only possible because we know the insights of the block code generation:

… but it does work. For the sake of completeness there is even another less elegant version where we create our own loop :wink: … I leave to the reader to find out why that one works (have a look into the generated code :wink: )

If you want, you can create an issue in github and we may add a special map for-loop in the future…

(actually tricking the blocks was quite fun for me - so thanks for bringing this up :D)

Perfect, solution worked for me.

Opened an issue at Blockly Dictionary loop block with value and key from dictionary · Issue #3373 · openhab/openhab-core · GitHub

And I provided an implementation for it today. Hope you like it.