Merging multiple dictionaries with cell arrays

43 views (last 30 days)
How can one merge multiple dictionaries A and B with cell arrays to get C. Ideally, with some warning for clashes.
A = dictionary( ...
{ ...
"type", ...
"value" ...
}, ...
{...
"temporary", ...
1 ...
} ...
)
A = dictionary (cell --> cell) with 2 entries: {["type"]} --> {["temporary"]} {["value"]} --> {[1]}
B = dictionary( ...
{ ...
"color" ...
}, ...
{...
"blue" ...
} ...
)
B = dictionary (cell --> cell) with 1 entry: {["color"]} --> {["blue"]}
C = dictionary( ...
{ ...
"type", ...
"value", ...
"color" ...
}, ...
{...
"temporary", ...
1, ...
"blue" ...
} ...
)
C = dictionary (cell --> cell) with 3 entries: {["type"]} --> {["temporary"]} {["value"]} --> {[1]} {["color"]} --> {["blue"]}

Accepted Answer

Stephen23
Stephen23 on 3 Jun 2025
Edited: Stephen23 on 3 Jun 2025
A = dictionary({"type","value"},{"temporary",1});
B = dictionary({"color"},{"blue"});
If you want to create a new merged dictionary without modifying the originals:
C = dictionary(A.keys, A.values);
C(B.keys) = B.values
C = dictionary (cell --> cell) with 3 entries: {["type"]} --> {["temporary"]} {["value"]} --> {[1]} {["color"]} --> {["blue"]}
If you can modify one of the original dictionaries:
A(B.keys) = B.values
A = dictionary (cell --> cell) with 3 entries: {["type"]} --> {["temporary"]} {["value"]} --> {[1]} {["color"]} --> {["blue"]}
You would have to experiment to find out how it behaves with duplicate keys.

More Answers (0)

Tags

Products


Release

R2025a

Community Treasure Hunt

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

Start Hunting!