IOS: how to join 2 Dictionaries into 1 dictionary?? - ios

in my project i applied the following code
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
diagnosedictforname = [[[dict6 objectForKey:#"diagnoses"]objectAtIndex:0]objectForKey:#"Diagnoses"];
NSLog(#" for ref id =%# ,name of diagnose=%# data is= %#",refidstr,diagnosedictforname ,diagnosisdict);
and the output in console is comes out as in the form
str : {
diagnoses = (
{
Diagnoses = {
"diagnosis_name" = "TRANSIENT ISCHEMIA";
};
DiagnosesHospitals = {
"charge_amt" = "1300.00";
discharges = "11200.00";
"hospital_id" = 3341;
id = 163080;
"medicare_amt" = "100.00";
"total_amt" = "1100.00";
};
}
);
response = 200;
}
ref id =3341 ,name of diagnose={
"diagnosis_name" = "TRANSIENT ISCHEMIA";
} data is= {
"charge_amt" = "1300.00";
discharges = "11200.00";
"hospital_id" = 3341;
id = 163080;
"medicare_amt" = "100.00";
"total_amt" = "1100.00";
}
now i just want to embed the values of both the Dictionaries into one dictionary
someone please help me to sort out this issue.

Make a mutable copy of the first dictionary:
NSMutableDictionary * mutDic = [dic1 mutableCopy];
and then:
[mutDic addEntriesFromDictionary:dic2];

Try this code:
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
NSMutableDictionary *diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
NSDictionary *diagnosedictforname = [[[dict6 objectForKey:#"diagnoses"]objectAtIndex:0]objectForKey:#"Diagnoses"];
NSArray *keys = [diagnosedictforname allKeys];
for (int i =0; i < keys.count; i++) {
NSString *key = [keys objectAtIndex:i];
[diagnosisdict setValue:[diagnosedictforname valueForKey:key] forKey:key];
}
NSLog(#"your dic -> %#", diagnosisdict);

Related

Searching in Dictionary of arrays in Objective C [duplicate]

i have a NSDictionary like:
{
"2017-05-02" = (
{
"always_valid" = 0;
date = "2017-05-02";
from = "12:00";
to = "13:00";
},
{
"always_valid" = 0;
date = "2017-05-02";
from = "12:00";
to = "12:00";
},
{
"always_valid" = 0;
date = "2017-05-02";
from = "14:00";
"hourly_rate" = 12;
to = "15:00";
}
);
"2017-05-03" = (
{
"always_valid" = 0;
date = "2017-05-03";
from = "12:00";
to = "13:00";
}
);
"2017-05-18" = (
{
"always_valid" = 1;
date = "2017-05-18";
from = "12:00";
to = "12:00";
}
);
}
i'm trying to apply
NSPredicate *filter = [NSPredicate predicateWithFormat:#"always_valid = \"1\""];
NSArray *alwaysvalid = [[dic allValues] filteredArrayUsingPredicate:filter];
it use to work when i had structure something like
array > dictionary
but now it's like
array > array > dictionary
by doing [dic allValues] for array.
any help what should i apply to keep it fast.
What you need to do is need enumerate your dictionary and create new filtered Dictionary.
NSMutableDictionary *filterDic = [[NSMutableDictionary alloc] init];
NSPredicate *filter = [NSPredicate predicateWithFormat:#"always_valid = 1"];
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSArray* obj, BOOL *stop) {
NSArray *filterArray = [obj filteredArrayUsingPredicate:filter];
if (filterArray.count > 0) {
filterDic[key] = filterArray;
}
}];
Try this :
NSArray *array = [NSArray arrayWithObject:dict]; // you can also do same for Name key...
NSArray *alwaysvalid = [array filteredArrayUsingPredicate:filter];

How to sort this NSDictionary based on its key "id" ascending order?

Hi This is what am getting from server
{
1 = {
"display_name" = "One";
id = 1;
};
2 = {
"display_name" = "Two";
id = 2;
};
13 = {
"display_name" = "abc";
id = 13;
};
15 = {
"display_name" = "aaa";
id = 15;
};
4 = {
"display_name" = "ffd";
id = 4;
};
3 = {
"display_name" = "abdfdfc";
id = 3;
};
5 = {
"display_name" = "aasdfsdfa";
id = 5;
};
}
i need to sort this based on "id" this is what am looking as output
Expecting output
{
1 = {
"display_name" = "One";
id = 1;
};
2 = {
"display_name" = "Two";
id = 2;
};
3 = {
"display_name" = "abdfdfc";
id = 3;
};
4 = {
"display_name" = "ffd";
id = 4;
};
5 = {
"display_name" = "aasdfsdfa";
id = 5;
};
13 = {
"display_name" = "abc";
id = 13;
};
15 = {
"display_name" = "aaa";
id = 15;
};
}
This code i have tried and its not working
//vehiclesDictionary real dictionary
NSMutableArray *sortedKeys=[[NSMutableArray alloc]init];
for(NSString *item in [vehiclesDictionary allKeys]){
[sortedKeys addObject:[NSNumber numberWithInt:[item intValue]]];
}
NSArray *sortedKeysArray = [sortedKeys sortedArrayUsingSelector: #selector(compare:)];
NSLog(#"%#",sortedKeysArray);
NSMutableDictionary *sortedValues = [[NSMutableDictionary alloc] init];
for (NSString *key in sortedKeysArray) {
[sortedValues setValue:[vehiclesDictionary valueForKey:[NSString stringWithFormat:#"%#",key]] forKey:key];
}
NSLog(#"%#",sortedValues);
Pls help me
You cannot sort an NSDictionary, it is an unsorted collection type. You will need to store your keys in an array and sort this and use it to access the NSDictionary in order.
Based on your code above, it could be modified as follows, e.g.
NSDictionary *dict = [NSDictionary dictionary];
NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector:#selector(compare:)];
for (NSString *key in sortedKeys) {
NSLog(#"%#", [d objectForKey:key]);
// Do something with the object here
}
Here you can pass around the sortedKeys array with the NSDictionary, and use the sortedKeys array for in-order access to your NSDictionary.
A more concise approach to get the array, but with the same outcome as above, would be using:
NSDictionary -keysSortedByValueUsingComparator as shown here.
As others have mentioned, NSDictionaries cannot be sorted. However, you could do something like this:
-(NSArray *)sortedKeysFromDictionary:(NSDictionary *)dictionary ascending:(BOOL)ascending
{
/* get all keys from dictionary */
NSArray *allKeys = [dictionary allKeys];
NSString *key = #"id"; // using "id" as key here
/* sort keys */
NSSortDescriptor *dateDescriptor = [NSSortDescriptor sortDescriptorWithKey:key ascending:ascending];
return [NSArray arrayWithArray:[allKeys sortedArrayUsingDescriptors:#[dateDescriptor]]];
}
This will take all the keys from your dictionary, sort them in ascending or descending order as you desire and return that as an NSArray. This array can then be used to access the original dictionary. A sample implementation would look something like this:
for (NSString *key in [self sortedKeysFromDictionary:sampleDic ascending:NO])
{
/* get value from current key */
NSDictionary *currentDic = [sampleDic objectForKey:key];
}

Convert NSString into NSDIctionary

I have a string ------ NSString abc = #"apple:87,banana:32,grapes:54";
i need this output like this
{
name = "apple";
value = "87";
},
{
name = "banana";
value = "32";
},
{
name = "grapes";
value = "54";
}
I have tried:
NSArray* itemList = [abc componentsSeparatedByString:#","];
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for (NSString* item in itemList) {
NSArray* subItemList = [item componentsSeparatedByString:#":"];
if (subItemList.count > 0) {
[dict setObject:[subItemList objectAtIndex:1] forKey:[subItemList objectAtIndex:0]];
}
}
NSLog(#"%#", dict);
The output is --
{
apple = 87;
banana = 32;
grapes = 54;
}
but i dont want this output
The wanted output is a NSArray of NSDictionary.
So:
NSArray* itemList = [abc componentsSeparatedByString:#","];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
for (NSString *aString in itemList)
{
NSArray* subItem = [aString componentsSeparatedByString:#":"];
NSDictionary *dict = #{#"name":[subItem objectAtIndex:0],
#"value":[subItem objectAtIndex:1]};
[finalArray addObject:dict];
}
I didn't use the if ([subItem count] > 0), trying just to keep the logic you missed and clarify the algorithm.
I didn't test the code, but that should do it. (or maybe a little compiler error easy to correct).
In case anyone wants the equivalent in Swift:
let abc = "apple:87,banana:32,grapes:54"
let dict = abc.componentsSeparatedByString(",").map { pair -> [String: String] in
let parts = pair.componentsSeparatedByString(":")
return ["name": parts[0], "value": parts[1]]
}

how to update NSMutableArray data depending on id or based on position

I have NSMutableArray data as below.
(
{
Id = 3;
Name = Fahim;
},
{
Id = 2;
Name = milad;
},
{
Id = 1;
Name = Test;
}
)
Now I want to update the name from Test to Omar (for id = 1).
Any idea how to get this done?
Answer
With below answer, I was getting error as -[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance. To resolve that issue I Changed [feeds addObject:[item copy]] to [feeds addObject:item]
for (NSMutableDictionary* aDict in yourMutableArray) {
if (aDict[#"id"] == 1) {
[aDict setObject:#"Omar" forKey:#"Name"];
}
}
EDIT :
NSMutableArray* mutableArray = [[NSMutableArray alloc]init];
NSDictionary* item1Dict = [NSDictionary dictionaryWithObjectsAndKeys:
#"1",#"id",
#"Fahim",#"name"
, nil];
NSMutableDictionary* item1 = [NSMutableDictionary dictionaryWithDictionary:item1Dict];
[mutableArray addObject:item1];
NSDictionary* item2Dict = [NSDictionary dictionaryWithObjectsAndKeys:
#"2",#"id",
#"milad",#"name"
, nil];
NSMutableDictionary* item2 = [NSMutableDictionary dictionaryWithDictionary:item2Dict];
[mutableArray addObject:item2];
NSDictionary* item3Dict = [NSDictionary dictionaryWithObjectsAndKeys:
#"3",#"id",
#"test",#"name"
, nil];
NSMutableDictionary* item3 = [NSMutableDictionary dictionaryWithDictionary:item3Dict];
[mutableArray addObject:item3];
NSLog(#"%#",mutableArray);
for (NSMutableDictionary* aDict in mutableArray) {
if ([aDict[#"id"] isEqualToString:#"3"]) {
[aDict setObject:#"Omar" forKey:#"name"];
}
}
NSLog(#"%#",mutableArray);
And for much elegant:
NSMutableArray* mutableArray = [[NSMutableArray alloc]init];
NSArray* name = [NSArray arrayWithObjects:#"Fahin",#"milad",#"test", nil];
for (int i = 0; i < name.count; i++) {
NSDictionary* itemd = [NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:#"%i",i],#"id",
name[i],#"name"
, nil];
NSMutableDictionary* item = [NSMutableDictionary dictionaryWithDictionary:itemd];
//or
//NSMutableDictionary* item = [item mutableCopy];
[mutableArray addObject:item];
}
NSLog(#"%#",mutableArray);
for (NSMutableDictionary* aDict in mutableArray) {
if ([aDict[#"id"] isEqualToString:#"2"]) {
[aDict setObject:#"Omar" forKey:#"name"];
}
}
NSLog(#"%#",mutableArray);
logs are:
2013-10-18 00:51:48.845 test[34919:60b] (
{
id = 1;
name = Fahim;
},
{
id = 2;
name = milad;
},
{
id = 3;
name = test;
}
)
second log:
2013-10-18 00:52:06.887 test[34919:60b] (
{
id = 1;
name = Fahim;
},
{
id = 2;
name = milad;
},
{
id = 3;
name = Omar;
}
)
EDIT2 for copy:
-copy, as implemented by mutable Cocoa classes, always returns their immutable counterparts. When an NSMutableDictionary is sent -copy, it returns an NSDictionary containing the same objects. NSMutableDictionary is a subclass of NSDictionary, the compiler doesn't complain. NSDictionary does not recognize it's mutable subclass' methods (because it cannot mutate it's contents).

count occurrences in a NSArray

this is a part of my code from a NSArray:
2012-06-03 16:03:45.140 test[4178:f803] data (
{
receiver = david;
sender = james;
idMessage = 248;
},
{
receiver = david;
sender = james;
idMessage = 247;
},
{
receiver = david;
sender = Marc;
idMessage = 246;
}
)
I want the number of messages sent by sender to receiver or something like that
james = 2;
marc = 1;
"data" is the NSArray, which appears to contain NSDictionary objects.
So you'd want to loop through the array this way:
NSNumber * countOfSender;
NSString * nameOfSender;
NSMutableDictionary * countDictionary = [[NSMutableDictionary alloc] initWithCapacity: 1];
// go through the original array to examine each sender
for(NSDictionary *anEntry in data)
{
nameOfSender = [anEntry objectForKey: #"sender"];
if(sender)
{
countOfSender = [countDictionary objectForKey: nameOfSender];
if(countOfSender == NULL)
{
// create a new count entry for this particular sender
countOfSender = [NSNumber numberWithInt: 1];
} else {
// increment the previous count
countOfSender = [NSNumber numberWithInt: [countOfSender intValue] + 1];
}
[countDictionary setObject: countOfSender forKey: nameOfSender];
}
}
// now print out the outputs
for(nameOfSender in [countDictionary allKeys])
{
countOfSender = [countDictionary objectForKey: nameOfSender];
NSLog( #"%# : %d" nameOfSender, [countOfSender intValue] );
}
You would do something like..
NSMutableArray *array = [NSMutableArray array];
for(id object in yourArray) {
NSLog("sender:%# id:%i",[object valueForKey:#"sender"],[[object valueForKey:#"idMessage"] intValue]);
NSMutableDictionary *dict = [
NSMutableDictionary dictionary];
[dict setValue:[object valueForKey:#"sender"] forKey:#"sender"];
[dict setValue:[NSNumber numberWithInt:[[object valueForKey:#"idMessage"] intValue]] forKey:#"idMessage"];
[array addObject:dict];
}
NSLog(#"%#",array);

Resources