5

In Bash (4 or above), if I have an associative array dict, I can set its value like dict[apple count]=1 and I would be able to access it with ${dict[apple count]}. Does Zsh allow space in key names? dict[apple count]=1 doesn’t work in Zsh, so I guess Zsh has different syntax for this. dict["apple count"]=1 doesn’t do what I want; instead of using apple count as the key, it is using "apple count" with quotation mark being part of the key.

Franklin Yu
  • 1,227
  • 12
  • 23

2 Answers2

5

One (ugly) workaround is to use the syntax to “append elements to an ordinary array”, like

dict+=('apple count' 1)

Zsh will maintain the property of associative arrays (as long as you declared it as one), so it will update the value if dict['apple count'] exists. A less ugly way since Zsh 5.5 is:

dict+=(['apple count']=1 ['orange count']=3)
Franklin Yu
  • 1,227
  • 12
  • 23
  • also `typeset 'dict[apple count]'=1` –  Feb 15 '21 at 08:02
  • or `typeset dict['apple count']=1` zsh is even more quirkier than bash lol –  Feb 15 '21 at 08:05
  • @user414777 Do I understand it correctly that by `typeset dict['apple count']=1` the built-in `typeset` actually see `dict[apple count]=1` as `$1`? – Franklin Yu Feb 16 '21 at 02:39
5

Zsh allows arbitrary strings as keys. The problem is with the parser.

To set an arbitrary key, using a variable works.

typeset -A dict
key='apple count'; dict[$key]=1
key=']'; dict[$key]=2
key=''; dict[$key]=3
printf %s\\n "${(k@)dict}"

Unsetting a key is more difficult.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175