Merging multiple dictionaries with dictionaries
Show older comments
Related to this question, how can one merge two dictionaries that have dictionaries as the keys and values?
A = dictionary(dictionary(["key1"], {1}), dictionary(["key2"], {2}));
A(dictionary(["key3"], {3})) = dictionary(["key4"], {4})
B = dictionary(dictionary(["key5"], {5}), dictionary(["key6"], {6}));
B(dictionary(["key7"], {7})) = dictionary(["key8"], {8})
C = dictionary(A.keys, A.values)
C(B.keys) = B.values
Accepted Answer
More Answers (2)
f=@(i) {dictionary(["key"+i], {i})}
A = dictionary(f(1), f(2));
A(f(3)) = f(4)
B = dictionary(f(5), f(6));
B(f(7)) = f(8)
C = dictionary(A.keys, A.values)
C(B.keys) = B.values
12 Comments
Matt J
on 12 Jul 2025
Correct. That is the form they must be in to be valid as keys/values.
When you call the keys() or values() command, the entries are concatenated together to form an array, e.g,
d=dictionary(1,2);
d(3)=4;
k=d.keys,
But it is not possible to concatentate dictionaries together. They can only exist as scalars.
Why does it bother you to wrap the dictionaries in cells?
I don't have to dereference (not sure that is the appropriate word in this context) the cell everytime I access the dicionaries.
You don't have to:
f=@(i) dictionary(["key"+i], {i});
k=arrayfun(f,1:4,'uni',0);
v=arrayfun(f,5:8,'uni',0);
C=dictionary(k, v)
C{k(1)}
Matt J
on 12 Jul 2025
That breaks the premise of your question. In the question, the keys of C were themselves dictionaries. Now, you say you want the keys of C to be the "subkeys" of A and B? And what about the values?
Maybe this is what you want?
f=@(i) dictionary(["key"+i], {i});
k=arrayfun(f,1:4,'uni',0);
v=arrayfun(f,5:8,'uni',0);
ksub=cell2mat( cellfun(@(c)c.keys,k,'uni',0) );
vsub=cell2mat( cellfun(@(c)c.keys,v,'uni',0) );
C=dictionary(ksub,vsub),
C("key2")
Maybe I don't have a necessary understanding of where the original dictionaries are coming from. Even before A, B are created, you apparently have a collection of multiple dictionaries from which A and B will be built. How are you holding this collection together?
It has to be with a cell array, becacuse again, dictionaries cannot be concatenated by themselves.There is no other way to maintain an array of dictionaries. And if the key/value dictionaries are already in cell form, why not continue to use them in that form?
James
on 12 Jul 2025
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!