My dictionary:
Dictionary<double, string> dic = new Dictionary<double, string>();
How can I return the last element in my dictionary?
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.
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.
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.
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).
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.
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