过滤和排序字典数组

时间:2012-09-24 14:01:25

标签: iphone ios cocoa nsdictionary

我有一个这样的主词典:

data = [{"key1": "value1", "key2": "value2", "key3": "value3"}, {"key1": "value1", "key2": "value5", "key3": "value6"}, {"key1": "value2", "key2": "value2", "key3": "value9"} ]

我需要创建一个字典,假设[value for "key1"][value for "key2"]有一个独特的组合:

即,我需要创建一个字典,如:

result = [{"value1" {"value2" : "value3", "value5" : "value6"}}, {"value2" {"value2" : "value9"}}]

1 个答案:

答案 0 :(得分:0)

我不确定我到底知道你在找什么,但这里有一个小程序可以做一些接近你所描述的事情。请注意,此问题与您标记的任何标记无关。这是一个基本的算法问题。

int main (int argc, const char * argv[]) {

    @autoreleasepool {

        NSArray *array = @[
            @{@"key1": @"value1", @"key2": @"value2", @"key3": @"value3"},
            @{@"key1": @"value1", @"key2": @"value5", @"key3": @"value6"},
            @{@"key1": @"value2", @"key2": @"value2", @"key3": @"value9"}
        ];

        NSMutableDictionary *result = [NSMutableDictionary dictionary];

        for (NSDictionary *dict in array) {
            [dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
                NSMutableArray *valuesForKey = [result objectForKey:key];
                if (valuesForKey == nil) {
                    valuesForKey = [NSMutableArray array];
                    [result setObject:valuesForKey forKey:key];
                }
                [valuesForKey addObject:value];
            }];
        }

        for (id key in result.allKeys) {
            NSMutableArray *valuesForKey = [result objectForKey:key];
            [valuesForKey sortUsingSelector:@selector(compare:)];
        }

        NSLog(@"Dictionary: %@", result);
    }
    return 0;
}

输出如下:

2012-09-24 20:44:02.509 Dummy[68684:303] Dictionary: {
    key1 =     (
        value1,
        value1,
        value2
    );
    key2 =     (
        value2,
        value2,
        value5
    );
    key3 =     (
        value3,
        value6,
        value9
    );
}