How to compare two dictionary key values and print

2019-09-14 05:00发布

I have two dictionary with multiple items. I want to compare values.

Dict1:{
"Displacement_trim" = "49.26 ";
"Dry_Weight" = "<null>";
}

Dict2:{
"Displacement_trim" = "171.20 ";
"Dry_Weight" = "<null>";
} 
  1. I want to know which "Displacement_trim" is greater.
  2. Also checking null values.
  3. Print the data in cell.

How can I achieve this?

2条回答
乱世女痞
2楼-- · 2019-09-14 05:29
NSMutableDictionary *dict1,*dict2;

 dict1 = [[NSMutableDictionary alloc]init];
dict2 = [[NSMutableDictionary alloc]init];

[dict1 setObject:[NSNumber numberWithFloat:13.20] forKey:@"Displacement_trim"];

[dict2 setObject:[NSNumber numberWithFloat:10.20] forKey:@"Displacement_trim"];

if ( [[dict1 valueForKey:@"Displacement_trim"] compare:[dict2 valueForKey:@"Displacement_trim"]]==NSOrderedAscending) {
    NSLog(@"dict 2 is greater");
}else{
    NSLog(@"dict 1 is greater");
}

Let me know if any thing get wrong.

查看更多
The star\"
3楼-- · 2019-09-14 05:47

To find out which value from the dict is bigger use the following code:

Swift 3

let dict1 = [ "Displacement_trim" : "49.26", "Dry_Weight" : "<null>" ]
let dict2 = [ "Displacement_trim" : "171.20", "Dry_Weight" : "<null>" ]

// I force unwrapped everything for brevity
if Float(dict1["Displacement_trim"]!)! > Float(dict2["Displacement_trim"]!)! {
    // highlight label for dict1
} else {
    // highlight label for dict2
}

Objective-C

NSDictionary *dict1 = @{@"Displacement_trim" : @"49.26", @"Dry_Weight" : @"<null>"};
NSDictionary *dict2 = @{@"Displacement_trim" : @"171.20", @"Dry_Weight" : @"<null>"};

NSString *dict1DisplacementTrim = dict1[@"Displacement_trim"];
NSString *dict2DisplacementTrim = dict2[@"Displacement_trim"];

if (dict1DisplacementTrim.floatValue > dict2DisplacementTrim.floatValue) {
    // highlight label for dict1
} else {
    // highlight label for dict2
}
查看更多
登录 后发表回答