Main Content

lookup

Find value in dictionary by key

Since R2023b

    Description

    example

    value = lookup(d,key) returns the value corresponding to key in dictionary, d. If no entry corresponds to key then lookup throws an error.

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

    example

    value = lookup(d,key,FallbackValue=fallback) specifies a fallback value to returned if key is not found in d.

    The lookup function does not validate fallback until a fallback value is required. An error is not thrown until key is not found, even if lookup is invalid.

    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"
    

    Look up a value.

    v = lookup(d,1)
    v = 
    "Unicycle"
    

    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"
    

    Look up a value with a fallback value if it is not found.

    v = lookup(d,[3,5],FallbackValue="Wheeled Vehicle")
    v = 1x2 string
        "Tricycle"    "Wheeled Vehicle"
    
    

    Input Arguments

    collapse all

    Dictionary, specified as a dictionary object. If d is unconfigured, lookup throws an error.

    Key set, specified as an array. The data type of key must match or be convertible to the data type of keys in d.

    Fallback value, specified as a scalar containing the value that to return if key is not found. The data type of fallback must match or be convertible to the data type of values in d. fallback is not validated until key is not found.

    Example: FallbackValue="Wheeled Vehicle"

    Version History

    Introduced in R2023b