Merging multiple dictionaries with dictionaries
조회 수: 14 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
Matt J
2025년 7월 12일
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});
kv = [keys(A, "cell")', keys(B, "cell")';
values(A, "cell")', values(B, "cell")'];
C=dictionary(kv{:})
댓글 수: 3
Matt J
2025년 7월 12일
편집: Matt J
2025년 7월 12일
But understand that if you now want to loop over the entries of C, you will need an array of its keys. Because the keys are dictionaries, the array will have to be in cell form:
k=[keys(A, "cell"); keys(B, "cell")];
v=[values(A, "cell"); values(B, "cell")];
%% noncell key/values
kv=[k';v'];
C=dictionary(kv{:})
for i=1:numel(k)
d=C(k{i})
end
But you could have implemented the same loop, with less code, by accepting cell-valued dictionary entries:
%% cell key/values
C=dictionary(k,v)
for i=1:numel(k)
d=C{k(i)}
end
추가 답변 (2개)
Matt J
2025년 7월 12일
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
Matt J
2025년 7월 12일
편집: Matt J
2025년 7월 12일
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?
참고 항목
카테고리
Help Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!