w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
NSDictionary refuses to set values for its keys.
You have a comment stating //Create a dictionary that holds the location data. but you never actually create it. Initialize the dictionary and you'll be fine. self.placeDictionary = [NSMutableDictionary dictionary]; Also beware: setValue:forKey: is not the same as setObject:forKey:. Read this answer to know more on the subject, but in general you should use setObject:forKey: for dictionaries, e.g. [self.placeDictionary setObject:@"155 Bovet Rd" forKey:@"Street"]; or the modern version of the syntax: self.placeDictionary[@"Street"] = @"155 Bovet Rd"; Using Objective-C literals you can actually make the whole code a lot nicer, check it out: self.placeDictionary = @{ @"Street": @"155 Bovet Rd", @"City" : @"san mateo", @"State" : @"ca", @"ZIP" : @"94402" };

Categories : Iphone

Ios NSDictionary array - grouping values and keys
You could create an NSMutableDictionary and loop through your array, adding the keys to the mutable dictionary using the allKeys. For example, if your array was called dictArray, you could do: NSMutableDictionary *combinedDictionary = [[NSMutableDictionary alloc] init]; for (NSDictionary *currentDictionary in dictArray) { NSArray *keys = [currentDictionary allKeys]; for (int n=0;n<[keys count];n++) { NSMutableDictionary *dictionaryToAdd = [combinedDictionary valueForKey:[keys objectAtIndex:n]]; if (!dictionaryToAdd) dictionaryToAdd = [[NSMutableDictionary alloc] init]; [dictionaryToAdd setValuesForKeysWithDictionary:[currentDictionary valueForKey:[keys objectAtIndex:n]]]; [combinedDictionary setValue:dictionaryToAdd forKey:[keys objectAtIndex:n]

Categories : Iphone

Create NSDictionary with keys and values when selected UICollectionViewCell
In your controller, declare a member variable NSMutableString *mutableString. Initialize mutableString in your init method to be empty. - (void)collectionView:(UICollectionView *)aCollectionView didSelectItemAtIndexPath:(NSIndexPath)indexPath { NSString *key = [NSString stringWithFormat:@"image[%d]", [indexPath row]]; NSString *value = // get the picture id NSString *parameter = [NSString stringWithFormat:@"%@=%@", key, value]; if ([mutableString length] != 0) [mutableString appendString:@"&"]; [mutableString appendString:parameter]; } Then use an IBAction to confirm the selections, construct your POST request and send it, and then empty the mutable string.

Categories : IOS

what's the best way to sort this NSArray of NSDictionary's with different keys but values of the same type
Maybe not the most efficient way ever, but this will do NSArray * d = @[@{@"world": @10}, @{@"hello": @5}, @{@"that": @3}, @{@"this": @1}]; [d sortedArrayUsingComparator:^NSComparisonResult(NSDictionary * obj1, NSDictionary * obj2) { NSNumber * v1 = obj1[[obj1 allKeys][0]]; NSNumber * v2 = obj2[[obj2 allKeys][0]]; return [v1 compare:v2]; }]; Anyway, the data organization is not very suitable for the task. Since the inner data structure is a dictionary, gathering the value is rather cumbersome. You may consider making the inner one an array.

Categories : Objective C

NSDictionary keys with @ symbol
As already stated you cannot do this. To Paraphrase Apple Docs reg. Key format - Keys must use ASCII encoding, begin with a lowercase letter, and may not contain whitespace. So trying to have a key with @.. as start isn't going to cut it. What I suggest you do is this - since you cannot change the way your backend sends the keys, you can control how those keys are represented in iOS. So Once you get the keys remove the starting @ symbol and insert the rest of the string as key. Since @ is constant across all keys, removing them from all keys should not affect cardinality of your dict.

Categories : IOS

Using nested keys in NSDictionary
It looks like you just have nested dictionaries, which you would access like so: branches[geoData][latitude] Are you certain this is an NSDictionary and not an object returned by JSON deserialization? The 2 code blocks don't match in any way, so it's difficult to give you a better answer. Are branches and dictionary the same object?

Categories : IOS

Dealing with nested NSDictionary keys
A couple things I'm seeing here. Seems like in your completion handler, you're calling out to your web service again. I don't think that's causing your issue, but it's something to look at. Specifically, this line: NSData *jsonData = [NSData dataWithContentsOfURL:url]; I think it should probably be: NSData *jsonData = data; The data is already being passed into your block, and you're already testing against it as an error condition above this. I don't think the data is formed the way you're expecting it to be formed. Unless the merchants names are all 36.xxxxx I wonder if you could print out the results (assuming no sensitive data is there) so we could see how it's structured? Maybe replace NSLog(@"Longitude: %@",[_result valueForKeyPath:@"merchants.branches.longitude"]); with NSL

Categories : IOS

Adding keys to Nested NSDictionary
The problem here has nothing to do with nesting. It has to do with mutable verse immutable. If the dictionary isn't mutable you can't add to it. The error message is telling you, that NSDictionary's don't have a method called setObject:ForKey: because that is a method of NSMutableDictionary. Using Apples new literal dictionaries @{ key: object} only creates immutable dictionaries. So what you actually need is to make sure you're created NSMutableDictionarys using either [NSMutableDictionary dictionaryWithObjectsAndKeys:]; or [@{ Key: Object } mutableCopy] So here is your code changed NSMutableDictionary *subNode = [NSMutableDictionary dictionaryWithObjectsAndKeys:@40, @"SubNode11", @30, @"SubNode12", nil]; NSMutableDictionary *Ga = [NSMutableDictionary dictionaryWithObjectsAndKeys:subN

Categories : Objective C

Array refuses to be returned with values
The problem is probably not that the data isn't being populated, but that you're alerting it too soon. jQuery's get is an asynchronous call, and it returns before the callback has processed. If you move the alert inside the get call, you should have your data. Data.prototype.fetchData = function(csv){ jQuery.get(csv, function(data) { var result = $.csv.toArrays(data); result.shift(); result.forEach(function (r) { var joinedResult = r.join(); fillDB(joinedResult); }); alert(getData()); }); };

Categories : Javascript

With fast enumeration and an NSDictionary, iterating in the order of the keys is not guaranteed – how can I make it so it IS in order?
Dictionaries are, by definition, unordered. If you want to apply an order to the keys, you need to sort the keys. NSArray *keys = [articles allKeys]; NSArray *sortedKeys = [keys sortedArrayUsingSelector:@selector(compare:)]; for (NSString *key in sortedKeys) { // process key } Update the way the keys are sorted to suit your needs.

Categories : IOS

ios - get values from NSDictionary
That error message is simply telling you that NSDictionary (which is the first object of that array, along with the second) doesn't respond to objectAtIndex. This will be a bit cody, but it explains it better: NSArray *jsonArray = [json allValues]; NSDictionary *firstObjectDict = [jsonArray objectAtIndex:0]; NSString *myValue = [firstObjectDict valueForKey:@"text"];

Categories : IOS

How do I retrieve values from NSDictionary?
JSON data would be in NSMutableArray format. NSMutableArray *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil]; int i=0; for (i=0;i<[allDataDictionary count];i++) { NSLog("value is %@", [NSString stringWithFormat:@"%@", [[allDataDictionary objectAtIndex:i] objectForKey:@"yourKey"]];) }

Categories : IOS

Get list of Values for an NSArray of NSDictionary
Try this: NSArray *myArray = @[@{@300:@"5 min"}, @{@900:@"15 min"}, @{@1800:@"30 min"}, @{@3600:@"1 hour"}]; NSMutableArray *keyArray = [[NSMutableArray alloc] init]; NSMutableArray *valueArray = [[NSMutableArray alloc] init]; for (NSDictionary *dictionary in myArray) { for (NSString *key in dictionary) { [keyArray addObject:key]; [valueArray addObject:[dictionary objectForKey:key]]; } }

Categories : Objective C

Getting values from nested NSDictionary in Order?
Fast enumeration pulls dictionary keys in implementation-defined order (specifically, in the order consistent with hash codes of that dictionary's keys). If you need to enforce a specific order, pull the keys out of the dictionary into NSArray, sort that array to your liking, and then fast-iterate the array, pulling values from the dictionary for each key in the sorted order: NSDictionary *dict = ... // You can use any of the sortedArrayUsingXYZ methods below NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingDescriptors:...]; for (NSString *key in sortedKeys) { id obj = [dict getObjectForKey:key]; ... }

Categories : IOS

NSDictionary using to get key values data in Nsarray
First you array with dictionary Look like this:- ( { "player_isblocked" = false; "player_level" = 1; "user_currency_code" = USD; "user_currency_symbol" = "$"; usertypecode = ROBT; } } i Test it using this code:- NSMutableArray *ar=[[NSMutableArray alloc]init]; NSMutableDictionary *dOfPerson=[NSMutableDictionary dictionary]; [dOfPerson setObject:[NSString stringWithFormat:@"USD"] forKey:@"user_currency_code"]; [dOfPerson setObject:[NSString stringWithFormat:@"$"] forKey:@"user_currency_symbol"]; [dOfPerson setObject:[NSString stringWithFormat:@"ROBT"] forKey:@"usertypecode"]; [dOfPerson setObject:[NSString stringWithFormat:@"1"] forKey:@"player_level"]; [dOfPerson setObject:[NSString stringWithFormat:@"false

Categories : IOS

How to extract an entry to nsdictionary base on a condition and copy it another array or nsdictionary
Yes, you can use keysOfEntriesPassingTest NSSet * selectedKeys = [Trailer keysOfEntriesPassingTest:^(id key, id obj, BOOL *stop) { return ![obj isEqualToString:@"Normal"]; }];

Categories : IOS

How can I alphabetically sort the values in my NSDictionary with an NSArray?
Your code is going to mean that mutarr is an array containing an array of arrays, not an array of strings. You should be looping over the array values from the dictionary and adding the items from each one to your mutarr to make it an array of strings that you can sort.

Categories : IOS

Sorting an NSDictionary based on the number of values be key
You need to create a new class that has countryName and a numberOfCities members. Once you've done this, you can create an array of these objects and sort them. For example, the custom object could have a header file similar to this: @interface Country : NSObject @property (nonatomic, strong) NSString *countryName; @property (nonatomic) NSUInteger numberOfCities; @end

Categories : IOS

Filter out certain array keys (and their values), while keeping other array keys and values
array_diff_key($arr, array_flip(array('foo', 'bar', ...))) http://php.net/array_diff_key The flip is just for convenience, you could also define the array of keys to remove using array('foo' => null, ...).

Categories : PHP

Retrieve values from NSDictionary (which is stored in a NS Mutable Array) from another class
You can just chain messages: NSDictionary* colorDict = [colors objectAtIndex:0]; UIColor *aminocolor = [colorDict objectForKey:@"1"]; Or the same in one line: UIColor *aminocolor = [[colors objectAtIndex:0] objectForKey:@"1"];

Categories : IOS

Adding NULL Values to SQLite Database with FMDB and NSDictionary
You can do it by not using the "fancy" withParameterDictionary method, and instead using the boring executeUpdate like this: NSString *addAircraftQuery = @"INSERT INTO aircrafts (aircraft_id, make_model, category_class, updated_flag) VALUES (?, ?, ?, ?)"; [db executeUpdate:addAircraftQuery, self.aircraftDict, self.makeModelTextField.text, self.categoryClassTextField.text, @YES];

Categories : IOS

The Idea? creating sorted array from NSDictionary key values (with objects)
Here's how I resolved this challenge. It works and was pretty straightforward to integrate into my Master/Detail project I know I found a tutorial on the web somewhere that led me to this solution , I'm sorry I can't find it now. Note that sortedDogDictionaryArray and dogDictionaryArray are declared as properties in the .h file. self.dogDictionaryArray = [vars.dogDictionary allValues]; // Sort NSSortDescriptor *sortDescriptorDog = [[NSSortDescriptor alloc] initWithKey:@"licenseString" ascending:YES]; NSArray *sortDescriptorsDogs = [NSArray arrayWithObject:sortDescriptorDog]; self.sortedDogDictionaryArray = [self.dogDictionaryArray sortedArrayUsingDescriptors:sortDescriptorsDogs]; NSLog(@"%@",self.sortedDogDictionaryArray ); int doggie; Dog *someDogName; NSLog(@"Sorted Order is...");

Categories : Sorting

NSDictionary to NSDictionary formatted string and back
Solved my problem, many thanks to the comments. To save in "human readable plist form"/"property list representation" (XML, etc) either use NSDictionary's writeToFile: method. Doc link or NSPropertyListSerialization dataWithPropertyList: method. Doc link NSError *error; dataToBeStored = [NSPropertyListSerialization dataWithPropertyList:dictionaryToBeStored format:NSPropertyListXMLFormat_v1_0 options:0 error:&error]; if (data) { NSFileManager* fileManager = [[NSFileManager alloc] init]; [fileManager createFileAtPath:fullPath contents:dataToBeStored attributes:nil]; [fileManager release]; } Now if you open the saved file up and read the data and convert to string you get a nice human readable plist. Or you can also init an NSDictionary with it.

Categories : Objective C

Create sorted array from multi-dimensional NSDictionary's sub-dictionary values
Check out NSDictionary method keysSortedByValueUsingComparator: You provide a comparator block that works on the values (your student dictionaries) and returns an array of keys. https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/doc/uid/20000140-SW21

Categories : IOS

Does the order of keys in dictionary.keys() in a python dictionary change if the values are changed?
No, a python dictionary has an ordering for the keys but does not guarantee what that order will be or how it is calculated. Which is why they are not guaranteed to be ordered in the first place. The values stored in the dictionary do not have an effect on the hash values of the keys and so will not change ordering. Taken from the Python Documentation: The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it). To check whether a single key is in the dictionary, use the in keyword.

Categories : Python

efficiently swap a python dict's keys and values where the values contain one or more elements
You can use defaultdict: from collections import defaultdict y = defaultdict(list) for key, values in x.items(): # .iteritems() in Python 2 for value in values: y[value].append(key)

Categories : Python

How to cast Django form to dict where keys are field id in template and values are initial values?
If you have the auto_id set to True then you can get the id with form_object_instance.field_name.auto_id. With that in mind you can create your dict by iterating over the form object. I am just wondering why you would need to do such a processing as the form object is usually used to encapsulate such behaviors...

Categories : Django

Check if an array of NSDictionary contains a NSDictionary
NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"%K LIKE[c] %@", @"name", @"htmlTitle"]; NSArray *theFilteredArray = [mainArrayOfDictionry filteredArrayUsingPredicate:aPredicate]; if ([theFilteredArray count]){ NSLog(@"Dictionay Exists"); }else{ NSLog(@"Dictionay does not Exists"); } In the first statement the first parameter is the "Key" and the second parameter is the actual value of the dictionay. I am Assuming following : NSDictionary *dictForJson = @{@"name": htmlTitle, @"src": path, @"expiryDate": expireDate}; NSArray *mainArrayOfDictionry = ( "dictForJson" : @{@"name": htmlTitle, @"src": path, @"expiryDate": expireDate}; ), (), (), (), . . . ) *Hope this will help you.*Arr

Categories : IOS

How to set keys and values of a hashmap as tags and values of a xml file
You can use @XmlAnyElement instead. @XmlAccessorType(XmlAccessType.FIELD) public class AlphabetReq { @XmlAnyElement private List<Element> allTags = new ArrayList<Element>(); List<Element> getAllTags() { return allTags; } void setAllTags(List<Element> allTags) { this.allTags = allTags; } public Map<String, String> getValues() { final Map<String, String> retVal = new HashMap<String, String>(); for (Element el : allTags) { retVal.put(el.getNodeName(), el.getTextContent()); } return retVal; } } method GetValues() returns value as expected: {f=Fox, d=Dog, e=Elephant, b=Ball, c=Cat, a=Apple} example: AlphabetReq obj = JAXB.unmarshal(new java.io.File

Categories : Java

Keep keys with their values after values have been sorted in array?
Don't sort the values alone, sort through a 2D array -- an array of arrays. so it will look something like Key1 | Val1 ----------- Key2 | Val2 ----------- Key3 | Val3 Then you sort based on the values, but you move both. When sorted, it might look like Key3 | Val3 ----------- Key1 | Val1 ----------- Key2 | Val2 And then when you're referring to the first value, you do array[0][1] and for the key to that value you would do array[0][0].

Categories : Javascript

AFNetworking sending NSDictionary as single array values instead of sending them as complete objects
I think the issue comes about because you're using a default HTTP POST with arguments to send your value. You can confirm this by printing out the content-type of the post on the server side; it should be something along the lines of x-www-form-urlencoded. If that's the case, that data format can't really express arrays and dictionaries well. So you get the odd format you're seeing on the server side. What you probably want to do is send your data as JSON, not as plain form parameters. I believe the thing you want to do is set the parameterEncoding property of your AFHTTPClient to AFJSONParameterEncoding. This will send your request as JSON, which is capable of representing arrays and dictionaries correctly on the wire.

Categories : IOS

iOS adding objects to NSDictionary and accessing the objects in the NSDictionary
First, you've got a naming conflict with your listOfClients local variable and your property. Try something like this: self.listOfClients = [[NSMutableDictionary alloc] init]; ObjectClass *myObject = [[ObjectClass alloc] init]; myObject.firstName = @"John"; myObject.lastName = @"Smith"; self.listOfClients[@"firstClient"] = myObject; This will accomplish initializing the dictionary and an object and placing the object in the dictionary. Then later you can access the item like this: ObjectClass *obj = (ObjectClass *)self.listOfClients[@"firstClient"]; NSLog(@"Name: %@ %@", obj.firstName, obj.lastName);

Categories : Iphone

How can i get the top n keys of std::map based on their values?
Not only does std::map not sort by mapped-to value (such values need not have any defined sorting order), it doesn't allow rearrangement of its elements, so doing ++ map[ "key1" ]; on a hypothetical structure mapping the values back to the keys would invalidate the backward mapping. Your best bet is to put the key-value pairs into another structure, and sort that by value at the time you need the backward mapping. If you need the backward mapping at all times, you would have to remove, modify, and re-add each time the value is changed. The most efficient way to sort the existing map into a new structure is std::partial_sort_copy, as (just now) illustrated by Al Bundy.

Categories : C++

How to get keys and values from a dictionary
Just iterate them directly in a nested loop Dictionary<DateTime, List<Double>> map; foreach (var pair in map) { DateTime dt = pair.Key; foreach (double value in pair.Value) { // Now you have the DateTime and Double values } }

Categories : C#

Cloning values of keys in Javascript
Let the groups to be extracted be grp[]. You can do something like this - // Extract groups in grp[] from origArray[] var extractGrps = function(grps, origArray) { var result = []; for(var i =0; i<grps.length; i+=1) { var indxInOrigArray = indexOfObjectWithKey(origArray, grps[i]); if(indxInOrigArray > 0) { var arrLocal = origArray[indxInOrigArray].grps[i]; for(var j=0; j<arrLocal.length;j+=1) result.push(arrLocal[j]); } } return result; } //find Index of object in arr whose key matches the given input key var indexOfObjectWithKey = function(arr, key) { for(var i=0; i<arr.length; i+=1) { if(arr[i].key) { return i; } } return -1; }

Categories : Javascript

Total values from all keys in subdocument
There isn't a way in the mongodb aggregation framework for treating a key inside of a document as data you can examine or manipulate. A workaround is to turn what you're using as keys here (e.g. fruit type and store name) into values like this: { "_id" : "doc1", "stores":[ { // store name is a value "name":"store_A", "inventory": [ { // so is fruit type "type" : "apple", "count" : 50 }, { "type" : "orange", "count" : 20 } ] }, { "name": "store_B", "inventory": [ { "type" : "orange", "count" : 15 }

Categories : Mongodb

How to add in a dictionary the values that have similar keys?
Take the first character of each key, call .upper() on that and sum your values by that uppercased letter. The following loop out = {} for key, value in original.iteritems(): out[key[0].upper()] = out.get(key[0].upper(), 0) + value should do it. You can also use a collections.defaultdict() object to simplify that a little: from collections import defaultdict: out = defaultdict(int) for key, value in original.iteritems(): out[key[0].upper()] += value or you could use itertools.groupby(): from itertools import groupby key = lambda i: i[0][0].upper() out = {key: sum(v for k, v in group) for key, group in groupby(sorted(original.items(), key=key), key=key)}

Categories : Python

Assigning arrays as keys and values of a map
You declared the map to use arrays of strings to be used. If you want to put(x,y) where x and y are String , then you have to declare it Map<String,String>. For your case, x would be one element of a , y an element of b. You'll have to iterate over a and b to insert all of them into the Map as you can see in various answers by now.

Categories : Java

PHP - Comparing Array Keys and Values
There is no need to iterate over an array when you know the key you are looking for. Simply check for the value using the key. if ( $mergedArrays[$username] == $password ) { return TRUE; }

Categories : PHP

Combining keys by similar values in PHP
You want to make $similars into an array of arrays. That way you can keep all the keys with that value. $results = array(); $similars = array(); foreach ($array as $k => $v) { if(!isset($similars[$v])){ $similars[$v] = array($k); } else{ $similars[$v][] = $k; } $results[$v] = implode(", ", $similars[$v]) . ' : ' . $v; } var_dump(implode(" ", $results));

Categories : PHP



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.