Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last element in a dictionary?

My dictionary:

Dictionary<double, string> dic = new Dictionary<double, string>(); 

How can I return the last element in my dictionary?

like image 300
subprime Avatar asked Jun 19 '09 14:06

subprime


People also ask

How do you end a dictionary in Python?

Delete elements of a dictionary To delete a key, value pair in a dictionary, you can use the del method. A disadvantage is that it gives KeyError if you try to delete a nonexistent key. So, instead of the del statement you can use the pop method. This method takes in the key as the parameter.

How do you slice a dictionary in Python?

To slice a dictionary, you can use dictionary comprehension. In Python, dictionaries are a collection of key/value pairs separated by commas. When working with dictionaries, it can be useful to be able to easily access certain elements.

How do you extract the first element from a dictionary?

Get first value in a dictionary using item() item() function of dictionary returns a view of all dictionary in form a sequence of all key-value pairs. From this sequence select the first key-value pair and from that select first value.

What does KEYS () do in Python?

keys() method in Python is used to retrieve all of the keys from the dictionary. The keys must be of an immutable type (string, number, or tuple with immutable elements) and must be unique. Each key is separated from its value by a colon(:). An item has a key and a value is stated as a pair (key : pair).


1 Answers

What do you mean by Last? Do you mean Last value added?

The Dictionary<TKey,TValue> class is an unordered collection. Adding and removing items can change what is considered to be the first and last element. Hence there is no way to get the Last element added.

There is an ordered dictionary class available in the form of SortedDictionary<TKey,TValue>. But this will be ordered based on comparison of the keys and not the order in which values were added.

EDIT

Several people have mentioned using the following LINQ style approach

var last = dictionary.Values.Last(); 

Be very wary about using this method. It will return the last value in the Values collection. This may or may not be the last value you added to the Dictionary. It's probably as likely to not be as it is to be.

like image 109
JaredPar Avatar answered Oct 09 '22 13:10

JaredPar