Contenuto principale

insert

Add entries to a dictionary

Since R2023b

    Description

    d2 = insert(d1,key,value) assigns the value to key in dictionary, d2. If key already has a corresponding value, then insert overwrites the value.

    d = insert(d,key,value) is equivalent to d(key) = value.

    example

    d2 = insert(d1,key,value,Overwrite=tf) specifies whether to overwrite an existing value corresponding to key.

    example

    Examples

    collapse all

    Create a dictionary containing several key-value pairs.

    names = ["Unicycle" "Bicycle" "Tricycle"];
    wheels = [1 2 3];
    d = dictionary(wheels,names)
    d =
    
      dictionary (double ⟼ string) with 3 entries:
    
        1 ⟼ "Unicycle"
        2 ⟼ "Bicycle"
        3 ⟼ "Tricycle"
    

    Insert a new entry.

    d = insert(d,4,"Car")
    d =
    
      dictionary (double ⟼ string) with 4 entries:
    
        1 ⟼ "Unicycle"
        2 ⟼ "Bicycle"
        3 ⟼ "Tricycle"
        4 ⟼ "Car"
    

    Create a dictionary containing several key-value pairs.

    names = ["Unicycle" "Bicycle" "Tricycle"];
    wheels = [1 2 3];
    d = dictionary(wheels,names)
    d =
    
      dictionary (double ⟼ string) with 3 entries:
    
        1 ⟼ "Unicycle"
        2 ⟼ "Bicycle"
        3 ⟼ "Tricycle"
    

    Insert new entries without overwriting existing entries.

    d = insert(d,[2 4],["Motorcycle" "Car"],Overwrite=false)
    d =
    
      dictionary (double ⟼ string) with 4 entries:
    
        1 ⟼ "Unicycle"
        2 ⟼ "Bicycle"
        3 ⟼ "Tricycle"
        4 ⟼ "Car"
    

    Input Arguments

    collapse all

    Input dictionary, specified as a dictionary object.

    Key set, specified as a scalar or an array. The data type of key must match or be convertible to the data type of keys in d. The size of key must be compatible with the size of value.

    Value set, specified as a scalar or an array. The data type of value must match or be convertible to the data type of values in d. The size of key must be compatible with the size of value.

    Option to overwrite existing entries, specified as true, false, 1 or 0. Specify a value of 0 or false to prevent insert from overwriting existing entries.

    Example: Overwrite=false

    Tips

    • A dictionary maps keys to values element-wise, allowing vectorized lookup and insert. Keys and values must each consist of elements of the same or compatible data type. To store nonscalar or heterogeneous values, use a cell array.

      For example, to insert tables as values in a dictionary:

      d = dictionary();
      t1 = table(1,2);
      t2 = table(1,2,3);
      d(["table1" "table2"]) = {t1,t2}
      d =
      
        dictionary (string ⟼ cell) with 2 entries:
      
          "table1" ⟼ {1×2 table}
          "table2" ⟼ {1×3 table}
      

    Extended Capabilities

    expand all

    Version History

    Introduced in R2023b

    expand all