Assign a value to a dictionary of dictionary

35 ビュー (過去 30 日間)
Ajay Reddy
Ajay Reddy 2023 年 5 月 6 日
コメント済み: chicken vector 2023 年 5 月 6 日
Hello everyone,
I have something like:
x = dictionary(dictionary()); % creating dictionary of dictionary
x_1 = dictionary; % creating a dictionary to map to x
x_1({[1,2,3]}) = 5; % assigning a cell as key and 5 as value
x(1) = x_1; % mapping 1 as key and x_1 as value to x
Now when I want to map something to the dictionary of x(1) how to perform it?
Something like this:
x(1)({[1,3,4]}) = 6; % this errors
But I am not able do something like this because of indexing issues
So I tried:
x_1 = x(1);
x_1({[1,3,4]}) = 6;
x(1) = x_1;
But this seems like a lot of time wasted, by making a copy of x(1) to x_1, and then performing the operation and mapping it back. Is there any better way to do this?
Thanks in advance!

採用された回答

chicken vector
chicken vector 2023 年 5 月 6 日
編集済み: chicken vector 2023 年 5 月 6 日
The impossibility of multiple indexing is a remarkable limitation that has also been discussed on the forum.
Unfortunately, I don't think there is an answer that might completely satisfy our needs of brevity.
A workaround for when you have only two layers of dictionaries is to use cells:
x = dictionary;
x_1 = dictionary;
x_1({[1,2,3]}) = 5;
x(1) = {x_1};
x{1}({[1,2,3]})
ans = 5
Otherwise you can use function handles for an indefinite number of subdictionaries:
getValue = @(dict,key) dict(key);
x = dictionary;
x_1 = dictionary;
x_1({[1,2,3]}) = 5;
x(1) = x_1;
getValue(getValue(x,1),{[1,2,3]})
ans = 5
  2 件のコメント
Ajay Reddy
Ajay Reddy 2023 年 5 月 6 日
Thanks a lot! It helped
chicken vector
chicken vector 2023 年 5 月 6 日
Glad it did

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeDictionaries についてさらに検索

製品


リリース

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by