I have one Dictionary and added some elements on it.for example,
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("Content","Level0");
d.Add("gdlh","Level1");
d.Add("shows","Level2");
d.Add("ytye","Level0");
In C#, Dictionary keeps elements in natural order.But i now want to iterate those values from last to first(ie, Reverse order).i mean,
first i want to read ytye then shows,gdlh and finally Content.
Please guide me to get out of this issue...
Use dict. items() to get a list of tuple pairs from d and sort it using a lambda function and sorted(). Use dict() to convert the sorted list back to a dictionary. Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the second argument.
Method #1 : Using OrderedDict() + reversed() + items() This method is for older versions of Python. Older versions don't keep order in dictionaries, hence have to converted to OrderedDict to execute this task.
Use the reversed() function to iterate over a list in reverse order, e.g. for item in reversed(my_list): . The reversed() function takes an iterator, such as a list, reverses it and returns the result.
Maybe OrderByDescending
on the key. Like this:
d.OrderByDescending (x =>x.Key)
Foreach
like this:
foreach (var element in d.OrderByDescending (x =>x.Key))
{
}
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