-1

我有一个像这样的主字典:

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"}}]
4

1 回答 1

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
    );
}
于 2012-09-24T18:47:20.547 回答