0

Can add() and insert() be performed on a dictionary? The help file is unclear on this. If so, what is the correct syntax?

If these functions do not work on dictionaries, then how can I add or insert items to the dictionary?

Tyler Durden
  • 2,091
  • 2
  • 23
  • 42

3 Answers3

6

Dictionaries aren't ordered, so there's no need for add() or insert().

Values are added to a dictionary using either

let d.foo = 'bar'

or

let d['foo'] = 'bar'

syntax.

I would also suggest reviewing :help 41.8 and :help Dictionary.

jamessan
  • 11,045
  • 2
  • 38
  • 53
2

Maybe you are looking to the wrong part of the documentation.

:help dict-functions

    Dictionary manipulation:                *dict-functions*
            get()           get an entry without an error for a wrong key
            len()           number of entries in a Dictionary
            has_key()       check whether a key appears in a Dictionary
            empty()         check if Dictionary is empty
            remove()        remove an entry from a Dictionary
   -->      extend()        add entries from one Dictionary to another
            filter()        remove selected entries from a Dictionary
            map()           change each Dictionary entry
            keys()          get List of Dictionary keys
            values()        get List of Dictionary values
            items()         get List of Dictionary key-value pairs
            copy()          make a shallow copy of a Dictionary
            deepcopy()      make a full copy of a Dictionary
            string()        String representation of a Dictionary
            max()           maximum value in a Dictionary
            min()           minimum value in a Dictionary
            count()         count number of times a value appears

Additional information and examples can be found at :help 41.8.

This only works for a key that is made of ASCII letters, digits and the
underscore.  You can also assign a new value this way: >

        :let uk2nl.four = 'vier'
        :echo uk2nl
    {'three': 'drie', 'four': 'vier', 'one': 'een', 'two': 'twee'}
mMontu
  • 6,630
  • 21
  • 31
  • This does not answer the question. I do not want to move entries from one Dictionary to another. I want to append and insert new entries. – Tyler Durden Jan 22 '18 at 21:24
  • @TylerDurden you could create a temporary dictionary to add the items, or add a item directly, as in the example above from :help 41.8. Try reading the documentation linked above. – mMontu Jan 23 '18 at 15:27
1

To add an item to an existing dictionary d, you could do let d['foo'] = 'bar', or use extend():

call extend(d, {'foo': 'bar'})
Flux
  • 1,041
  • 1
  • 11
  • 25