MATLAB 2022b新增了
dictionary
对象。在MATLAB文档中可以找到完整的使用指南,具体位置在
语言基础 > 数据类型 > 字典。
现在推荐使用
dictionary
而不是旧的
containers.Map
。引用
containers.Map
的文档:
dictionary
推荐使用,因为它接受更多的数据类型作为键和值,并提供更好的性能。(自R2022b起)
来自
R2022b版本说明:
在几乎所有的使用情况下,`dictionary` 的性能比 `containers.Map` 更快。
关于 `containers.Map` 的使用方法,请参考
Amro's answer。
构建字典可以通过传递具有相同数量条目的键和值数组来实现初始条目的集合:
% From key and value arrays
>> d = dictionary(["a", "b", "c"], [1, 2, 3])
d =
dictionary (string ⟼ double) with 3 entries:
"a" ⟼ 1
"b" ⟼ 2
"c" ⟼ 3
或者,初始条目可以作为键值对提供:
% Using Name=Value syntax (string keys only)
>> d = dictionary(a=1, b=2, c=3)
d =
dictionary (string ⟼ double) with 3 entries:
"a" ⟼ 1
"b" ⟼ 2
"c" ⟼ 3
>> squares = dictionary(2, 4, 3, 9, 4, 16)
squares =
dictionary (double ⟼ double) with 3 entries:
2 ⟼ 4
3 ⟼ 9
4 ⟼ 16
创建一个未配置的字典,您可以使用没有任何输入的
dictionary
。
>> d_unconfigured = dictionary
d_unconfigured =
dictionary with unset key and value types.
字典将在您分配一个条目后进行配置。
要构建一个具有预配置键和值类型的空字典,您可以使用
configureDictionary
(R2023b或更高版本):
>> d_empty = configureDictionary("string", "double")
d_empty =
dictionary (string ⟼ double) with no entries.
查找
单个键:
>> d("a")
ans =
1
同时查找一个键数组:
>> k = [ "a" "b"
"b" "c" ];
>> d(k)
ans =
1 2
2 3
无效的键查找错误。
>> d("bad key")
Error using ()
Key not found.
>> d(123)
Error using ()
Key not found.
MATLAB R2023b 引入了
lookup
函数,它允许您指定一个备用值:
>> d.lookup("a", FallbackValue=nan)
ans =
1
>> d.lookup("missing", FallbackValue=nan)
ans =
NaN
任务
>> d("new") = 10
d =
dictionary (string ⟼ double) with 4 entries:
"a" ⟼ 1
"b" ⟼ 2
"c" ⟼ 3
"new" ⟼ 10
如果可以进行转换,值将自动转换为值类型。如果无法进行转换,则会发出错误提示。
d("new") = "123" % Note: string instead of double
d =
dictionary (string ⟼ double) with 4 entries:
"a" ⟼ 1
"b" ⟼ 2
"c" ⟼ 3
"new" ⟼ 123
>> d("new") = @sum
Error using ()
Unable to use 'function_handle' as value for dictionary with 'double' value type.
Caused by:
Conversion to double from function_handle is not possible
删除
可以通过将一个空数组[]
赋值给键来删除它们:
>> d("a") = []
d =
dictionary (string ⟼ double) with 2 entries:
"b" ⟼ 2
"c" ⟼ 3
键的数组也可以在左侧使用,就像在上面的赋值中所看到的那样。
MATLAB 2023b引入了remove
函数,其行为与赋值[]
完全相同。
>> d.remove("a")
ans =
dictionary (string ⟼ double) with 2 entries:
"b" ⟼ 2
"c" ⟼ 3
尺寸
条目数量:
>> d.numEntries
ans =
3
提取键/值集合
键和值数组:
>> d.keys
ans =
3×1 string array
"a"
"b"
"c"
>> d.values
ans =
1
2
3
条目 表格:
>> d.entries
ans =
3×2 table
Key Value
___ _____
"a" 1
"b" 2
"c" 3
查询类型配置
查询键和值的类型:
>> [kt, vt] = d.types
kt =
"string"
vt =
"double"
检查字典是否配置了键和值的类型:
>> d.isConfigured
ans =
logical
1
没有任何初始条目的构建的词典是未配置的。
>> d2 = dictionary
d2 =
dictionary with unset key and value types.
>> d2.isConfigured
ans =
logical
0
>> [kt, vt] = d2.types
kt =
<missing>
vt =
<missing>
未配置的字典在分配条目后立即配置完成。
>> d2("key") = "value"
d2 =
dictionary (string ⟼ string) with 1 entry:
"key" ⟼ "value"
>> d2.isConfigured
ans =
logical
1
dictionary
现在被推荐使用,而不是containers.Map
。我在下面的答案中添加了一个链接,说明如何使用dictionary
。 - undefined