Create alphabetical NSDictionary from NSArray [closed] - ios

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Let's say I have an array that looks like this:
NSArray *array = #[#"Bear", #"Black Swan", #"Buffalo", #"Camel", #"Cockatoo", #"Dog", #"Donkey", #"Emu"]
How can I create following dictionary out of it?
NSDictionary *animals;
animals = #{#"B" : #[#"Bear", #"Black Swan", #"Buffalo"],
#"C" : #[#"Camel", #"Cockatoo"],
#"D" : #[#"Dog", #"Donkey"],
#"E" : #[#"Emu"]};

If I understand the question correctly you are trying to create a dictionary out of an array.
Try this:
NSArray *array = #[#"Bear", #"Black Swan", #"Buffalo", #"Camel", #"Cockatoo", #"Dog", #"Donkey", #"Emu"];
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
for (NSString *animal in array) {
NSString *firstLetter = [animal substringToIndex:1];
if (!dictionary[firstLetter]) {
dictionary[firstLetter] = [[NSMutableArray alloc] init];
}
[((NSMutableArray *)dictionary[firstLetter]) addObject:animal];
}
At the end the value of dictionary is:
dictionary = #{#"B" : #[#"Bear", #"Black Swan", #"Buffalo"],
#"C" : #[#"Camel", #"Cockatoo"],
#"D" : #[#"Dog", #"Donkey"],
#"E" : #[#"Emu"]};

I think you want to do this by :
NSMutableDictionary* animals =[NSMutableDictionary new];
NSArray* wAnimals =#[#"Whale", #"Whale Shark", #"Wombat"];
[animals setObject:wAnimals forKey:#"W"];

Please try this (Hope this will help you and i think you want like this)-
-(NSDictionary*)makeCustomDictionary:(NSString*)yourValue{
[array addObject:yourValue];
NSMutableArray *lettersKey = [NSMutableArray array];
NSMutableArray *values = [NSMutableArray array];
for (NSString *string in array) {
if (string.length > 0) {
NSString *letter = [string substringToIndex:1];
if (![lettersKey containsObject:letter]) {
[lettersKey addObject:letter];
NSString *stringToSearch = letter;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF beginswith[c] %#",stringToSearch]; // if you need case sensitive search avoid '[c]' in the predicate
NSArray *results = [array filteredArrayUsingPredicate:predicate];
[values addObject:results];
}
}
}
return [NSDictionary dictionaryWithObjects:values forKeys:lettersKey];
}
- (IBAction)addNewValue:(id)sender {
NSDictionary *tempDic=[self makeCustomDictionary:txt.text];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tempDic
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"dictionary in json form - %# \n\n or dictionary simple- %#",jsonString,tempDic);
}
}
here array is global NSMutableArray initialize in viewDidLoad().
Output-
dictionary in json form -
{
"D" : ["Dog","Donkey"],
"B" : ["Bear","Black Swan","Buffalo"],
"G" : ["Giraffe"],
"E" : ["Emu"],
"C" : ["Camel","Cockatoo"]
}
or dictionary simple- {
B = (
Bear,
"Black Swan",
Buffalo
);
C = (
Camel,
Cockatoo
);
D = (
Dog,
Donkey
);
E = (
Emu
);
G = (
Giraffe
);
}

Related

How to IntersectSet of two NSDictionary or NSMutableDictionary with values?

Want to merge two NSDictionary or NSMutableDictionary only with dict1 values. like [NSMutableDictionary addEntriesFromDictionary:] and intersectSet (from NSMutableSet).
Dict 1 = #{#”One”: #””, #”Two”: #”"}
Dict 2 = #{#”One”: #”1”, #”Two”: 2, #”Three”: #”3"}
My expect output after merge = #{#”One”: #”1”, #”Two”: #”2"}
UPDATE
I am already tried with [Dict1 addEntriesFromDictionary:Dict2] this one give answer #{#”One”: #”1”, #”Two”: 2, #”Three”: #”3"}
Also I am tried with NSMutableSet
NSMutableSet *keysInA = [NSMutableSet setWithArray:tempDict.allKeys];
NSSet *keysInB = [NSSet setWithArray:tempDict1.allKeys];
[keysInA intersectSet:keysInB];
NSLog(#"keys in A that are not in B: %#", keysInA);
This one give output One, Two, Three.
So [NSMutableSet setWithArray:] and [NSMutableDictionary addEntriesFromDictionary:] won't give what I expected.
If above code have anything work let clear me. Thanks.
NSDictionary *dict1 = #{#"One": #"", #"Two": #"6"};
NSDictionary *dict2 = #{#"One": #"1", #"Two": #"2", #"Three": #"3"};
NSDictionary * dict = [dict2 dictionaryWithValuesForKeys:[dict1 allKeys]];
NSLog(#"dict %#",dict);
// Log value
dict {
One = 1;
Two = 2;
}
Here what I expected.
try this...
//Assuming both dictionaries have same kind of keys
NSMutableDictionary *dict1 = #{#"One" : #"", #"Two": #"", #"Three" : #""}.mutableCopy;
NSDictionary *dict2 = #{#"One" : #"1", #"Two": #"2", #"Three" : #"3",#"Four":#"4"};
for (NSString *key in dict1.allKeys)
{
if (dict2[key])
{
dict1[key] = dict2[key];
}
}
NSLog(#"Updated dict %#",dict1);

how to get nsDictionary element by using for-in

NSDictionary *myDict = #{#"one":#"1",#"two":#"2"};
for (NSDictionary* tmp in myDict) {
NSLog(#"%#",tmp);
}
resut:
my tmpis NSString
I want to get a dictionary with key= one , value = 1
for in for NSDictionary will iterate the keys.
for (NSString * key in myDict) {
NSLog(#"%#",key);
NSString * value = [myDict objectForKey:key];
}
If you want to get a dictionary. You have to create a dictionary from these values
for (NSString * key in myDict) {
NSLog(#"%#",key);
NSString * value = [myDict objectForKey:key];
NSDictionary * dict = #{key:value};
}
Or you should init like this:
NSArray *arrDict = #[{#{"one":#"1"},#{#"two":#"2"}];
for (NSDictionary* tmp in arrDict) {
NSLog(#"%#",tmp);
}
You can get all keys from your dic then add the key and value to your new dic like this:
NSDictionary *myDict = #{#"one":#"1",#"two":#"2"};
NSArray *keys = [myDict allKeys];
for (NSString *key in keys) {
NSDictionary *yourDic = #{key: [myDict valueForKey:key]};
NSLog(#"%#", yourDic);
}
You didn't create it that way. If you wanted to have a NSDictionary inside another NSDictionary you should write something like this :
NSDictionary *myDict = #{
#"firstDict" : #{
#"one":#"1"
},
#"secondDict": #{
#"two":#"2"
}
};
Above code will create a NSDictionary with two dictionaries at keys #firstDict and #secondDict.
Also, bear in mind, that because dictionaries are key-value pairs, using a for-in loop, actually loops through the keys in that dictionary. So your code is equivalent to:
for(NSString *key in dict.allKeys) { ... }
I got the solution
NSDictionary *myDict = #{#"one":#"1",#"two":#"2"};
NSMutableArray *arrayObject = [[NSMutableArray alloc]init];
NSMutableArray *arrayKey = [[NSMutableArray alloc]init];
NSMutableArray *arrayObjectKey = [[NSMutableArray alloc]init];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
for (NSString *stringValue in myDict.allValues)
{
[arrayObject addObject:stringValue];
}
for (NSString *stringKey in myDict.allKeys)
{
[arrayKey addObject:stringKey];
}
for(int i = 0;i<[arrayKey count];i++)
{
dict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:#"%#",[arrayKey objectAtIndex:i]],#"key",nil];
[dict setObject:[NSString stringWithFormat:#"%#",[arrayObject objectAtIndex:i]] forKey:#"value"];
[arrayObjectKey addObject:dict];
}
NSLog(#"The arrayObjectKey is - %#",arrayObjectKey);
The Output is
The arrayObjectKey is -
(
{
key = one;
value = 1;
},
{
key = two;
value = 2;
}
)
Create the dictionary:
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:#"1",#"One",#"2","Two",nil];
Get a value out using:(this example tmp will be 1)
NSString *tmp = [myDict objectForKey:#"One"];
Display the output in console:
NSLog(#"%#",tmp);
To display the whole NSDictionary
NSLog (#"contents of myDict: %#",myDict);
What you are doing is creating a dictionary with key-value pairs. I think what you want to do is have an array with dictionaries.
NSArray *myArray = #[#{#"one":#"1"}, #{#"two":#"2"}];
for (NSDictionary* tmp in myArray) {
NSLog(#"%#",tmp);
}
However I don't see a point in doing this. What you could do is:
NSDictionary *myDict = #{#"one":#"1",#"two":#"2"};
for (NSString* key in [myDict allKeys]) {
NSLog(#"%# = %#", key, myDict[key]);
}

NSMutableDictionary setValue:/forKey:? [duplicate]

This question already has answers here:
Sort array into dictionary
(5 answers)
Closed 7 years ago.
I have a NSMutableArray named animals. I need to create an NSMutableDictionary such that all names in the animals array have Keys that start with a specific first letter = Values.
This is animals array :
NSMutableArray *animals = [NSMutableArray arrayWithObjects:#"Bear", #"Black Swan", #"Buffalo", #"Camel", #"Cockatoo", #"Dog", #"Donkey", #"Emu", #"Giraffe", #"Greater Rhea", #"Hippopotamus", #"Horse", #"Koala", #"Lion", #"Llama", #"Manatus", #"Meerkat", #"Panda", #"Peacock", #"Pig", #"Platypus", #"Polar Bear", #"Rhinoceros", #"Seagull", #"Tasmania Devil", #"Whale", #"Whale Shark", #"Wombat", nil];
this is my code to set it into a MutableDictionary :
for(NSString *str in animals) {
NSString *firstLetter = [str substringToIndex:1];
NSArray *newArr = [NSArray arrayWithObject:str];
[myMutableDictionary setValue:newArr forKey:firstLetter];
}
The problem is that for each key only one value is set, but i need all the objects have a first letter with the same value. E.g. value='b' -> #"Bear", #"Black Swan", #"Buffalo".
Try
for (NSString *str in animals) {
NSString *firstLetter = [str substringToIndex:1];
if(!myMutableDictionary[firstLetter])
{
myMutableDictionary[firstLetter] = [NSMutableArray new];
}
NSMutableArray *arr = myMutableDictionary[firstLetter];
[arr addObject:str];
}
Here are the code that satisfied your requirement.
Step 1 : Allocate NSMutableDictionary.
Step 2 : While parsing NSArray, check initial is there key available in dictionary or what. if available then that array from same key and add new element in array and update same key in dictionary. if not available then create new key in dictionary. here is code.
NSMutableDictionary* dictTemp = [[NSMutableDictionary alloc]init];
for (NSString *str in animals) {
NSString *firstLetter = [str substringToIndex:1];
if([[dictTemp allKeys] containsObject:firstLetter]){
NSMutableArray* arrayInner = [NSMutableArray arrayWithArray:[dictTemp valueForKey:firstLetter]];
[arrayInner addObject:str];
[dictTemp setValue:arrayInner forKey:firstLetter];
}
else{
NSMutableArray* arrayInner = [[NSMutableArray alloc] init];
[arrayInner addObject:str];
[dictTemp setValue:arrayInner forKey:firstLetter];
}
}
NSLog(#"Output : %#",dictTemp);

How to replace the value of the key in NSMutableDictionary based on the another key value pair

I have one NSArray with NSMutableDictionaries .Example testArray =[dict1,dict2,dict3,dict4].
Each dictionary in the array is something like
dict1= {
country = "INDIA";
flag = "A";
Currency = "Rupees";
rate = 10;
}
The all values are changeable. Sometimes
dict1 = {
country = "USA";
flag = "SA";
Currency = "Dollar";
rate = 50;
}
I need to update the value of the key rate of all dictionaries in the testArray if country = "INDIA" and flag = "A" and Currency = "Rupees" and Do not need to change the value of the rate key all other dictionaries in side the testArray.
Just try the below.
for(NSMutableDictionary *dic in array)
{
if([[dic valueForKey:#"country"] isEqualToString:#"INDIA"] &&
[[dic valueForKey:#"flag"] isEqualToString:#"A"] &&
[[dic valueForKey:#"Currency"] isEqualToString:#"Rupees"])
{
[dic setValue:#"100" forKey:#"rate"];
}
}
Here is a complete example what you need
NSDictionary *dict1 = #{
#"country" : #"INDIA",
#"flag" : #"A",
#"Currency" : #"Rupees",
#"rate" : #10
};
NSDictionary *dict2 = #{
#"country" : #"USA",
#"flag" : #"SA",
#"Currency" : #"Dollar",
#"rate" : #50
};
NSArray *testArray = #[dict1, dict2];
NSMutableArray *testMutableArray = [testArray mutableCopy];
for (int i = 0; i < testMutableArray.count; i++) {
NSDictionary *country = testMutableArray[i];
if ([country[#"country"] isEqualToString:#"INDIA"] &&
[country[#"flag"] isEqualToString:#"A"] &&
[country[#"Currency"] isEqualToString:#"Rupees"])
{
NSMutableDictionary *countryMutable = [country mutableCopy];
countryMutable[#"rate"] = #100;
testMutableArray[i] = [countryMutable copy];
}
}
testArray = [testMutableArray copy];
Use NSMutableArray instead of NSArray.
then,
NSDictionary *dict = [testArray objectAtIndex:0];
dict[#"rate"] = #"11";
[testArray replaceObjectAtIndex:0 withObject:dict];
Hope this will help you.

ios distinctUnionOfObjects is not returning all the content of dictionaries

I have an NSArray with NSDictionary and trying to remove duplicate with the following code:
NSDictionary *arnold = #{#"name" : #"arnold", #"state" : #"california"};
NSDictionary *jimmy = #{#"name" : #"jimmy", #"state" : #"new york"};
NSDictionary *henry = #{#"name" : #"henry", #"state" : #"michigan"};
NSDictionary *woz = #{#"name" : #"woz", #"state" : #"california"};
NSArray *people = #[arnold, jimmy, henry, woz];
NSMutableArray *results=[[NSMutableArray alloc]initWithArray: [people valueForKeyPath:#"#distinctUnionOfObjects.state"]];
NSLog(#"results %#", results);
this is the output I get from the nslog:
results (
california,
michigan,
"new york"
)
My question is how to add the full directories to the array?
#distinctUnionOfObjects will only returns the unique object value specified that property, not the objects themselves.
You may try this:
NSDictionary *arnold = #{#"name" : #"arnold", #"state" : #"california"};
NSDictionary *jimmy = #{#"name" : #"jimmy", #"state" : #"new york"};
NSDictionary *henry = #{#"name" : #"henry", #"state" : #"michigan"};
NSDictionary *woz = #{#"name" : #"woz", #"state" : #"california"};
NSArray *people = #[arnold, jimmy, henry, woz];
NSMutableArray *uniqueArray = [[NSMutableArray alloc] init];
NSMutableSet *checkedStates = [[NSMutableSet alloc] init];
for (NSDictionary *person in people) {
NSString *currentStateName = person[#"state"];
BOOL isDuplicateState = [checkedStates containsObject:currentStateName];
if (!isDuplicateState) {
[uniqueArray addObject:person];
[checkedStates addObject:currentStateName];
}
}
NSLog(#"Results %#", uniqueArray);
The output from NSLog will be:
Results (
{
name = arnold;
state = california;
},
{
name = jimmy;
state = "new york";
},
{
name = henry;
state = michigan;
}
)

Resources