Assign a value to a dictionary of dictionary

41 Ansichten (letzte 30 Tage)
Ajay Reddy
Ajay Reddy am 6 Mai 2023
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!

Akzeptierte Antwort

chicken vector
chicken vector am 6 Mai 2023
Bearbeitet: chicken vector am 6 Mai 2023
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

Weitere Antworten (0)

Kategorien

Mehr zu Dictionaries finden Sie in Help Center und File Exchange

Produkte


Version

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by