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.

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)
3
  • also typeset 'dict[apple count]'=1 – user414777 Feb 15 at 8:02
  • or typeset dict['apple count']=1 zsh is even more quirkier than bash lol – user414777 Feb 15 at 8: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 at 2:39
4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.