I have this code
NSDictionary *tempDict = [NSDictionary dictionaryWithObjects:
[NSArray arrayWithObjects:@"authorId","authorName","authorDescription",@"image",nil] forKeys:
[NSArray arrayWithObjects:@"id",@"name",@"desc",@"image",nil]];
NSLog(@"%@",[tempDict description]);
and the output is
desc = authorDescription;
id = authorId;
image = image;
name = authorName;
You see that the dictionary is sorted by key, alphabetically, for some reason. This is not good for me, because I need to add this dictionary to a plist, and this plist already has some dictionaries with unsorted keys. So how can I avoid this sorting?
Using items () alone: The method items () is used alone with two variables i.e., key and value to sort the dictionary by value. Below is the implementation using method items (): Using sorted () and get (): The method get () returns the value for the given key, if present in the dictionary. If not, then it will return None.
Below is the implementation using Counter from collections: Reverse Sorting Dictionary by values: The same syntax for both ascending and descending ordered sorting. For reverse sorting, the idea is to use reverse = true. with the function sorted (). Writing code in comment?
For reverse sorting, the idea is to use reverse = true. with the function sorted (). Writing code in comment? Please use ide.geeksforgeeks.org , generate link and share the link here.
Using sorted () and get (): The method get () returns the value for the given key, if present in the dictionary. If not, then it will return None. Below is the implementation using sorted () and get () method: The method itemgetter (n) constructs a callable that assumes an iterable object as input, and fetches the n-th element out of it.
The sorting is due to [NSDictionary description]
, which is used by NSLog
. It's not a fundamental feature of NSDictionary
. If you access the keys through fast enumeration or [dictionary allKeys]
, you won't find it sorted.
But to your underlying question, if what you want is "unsorted" (random), then "sorted" is just one of the possible random sequences. If you really want unsorted, then sorted shouldn't matter because its a subset.
If sorting matters, then you don't mean "unsorted," you mean "some other sorted order, such as insertion order." If you need NSDictionary
to be sorted in some way, you need to impose that by converting it into an NSArray
.
It's not sorted. It's displaying in an arbitrary order. Add some more items and you'll probably see the order change.
(It's possible that, internally, the storage is, for some mad reason, actually sorted, but there's nothing you can do about that.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With