I need to merge two NSDictionary
s into one provided that if there are dictionaries within the dictionaries, they are also merged.
More or less like jQuery's extend
function.
For anyone with lists as the final nested level under the dicts, you can do this instead of raising the error to concatenate the two lists: a[key] = a[key] + b[key] . Thanks for the helpful answer. > if you want to keep a you could call it like merge(dict(a), b) Note that nested dicts will still be mutated.
In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.
Dictionaries can be nested to any depth. Dictionaries are mutable. All the keys in a dictionary must be of the same type.
NSDictionary+Merge.h
#import <Foundation/Foundation.h>
@interface NSDictionary (Merge)
+ (NSDictionary *) dictionaryByMerging: (NSDictionary *) dict1 with: (NSDictionary *) dict2;
- (NSDictionary *) dictionaryByMergingWith: (NSDictionary *) dict;
@end
NSDictionary+Merge.m
#import "NSDictionary+Merge.h"
@implementation NSDictionary (Merge)
+ (NSDictionary *) dictionaryByMerging: (NSDictionary *) dict1 with: (NSDictionary *) dict2 {
NSMutableDictionary * result = [NSMutableDictionary dictionaryWithDictionary:dict1];
[dict2 enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
if (![dict1 objectForKey:key]) {
if ([obj isKindOfClass:[NSDictionary class]]) {
NSDictionary * newVal = [[dict1 objectForKey: key] dictionaryByMergingWith: (NSDictionary *) obj];
[result setObject: newVal forKey: key];
} else {
[result setObject: obj forKey: key];
}
}
}];
return (NSDictionary *) [[result mutableCopy] autorelease];
}
- (NSDictionary *) dictionaryByMergingWith: (NSDictionary *) dict {
return [[self class] dictionaryByMerging: self with: dict];
}
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With