Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first element from a dictionary

I have the following declaration:

Dictionary<string, Dictionary<string, string>> like = new Dictionary<string, Dictionary<string, string>>(); 

I need to get the first element out, but do not know the key or value. What's the best way to do this?

like image 793
cdub Avatar asked Dec 20 '12 20:12

cdub


People also ask

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.

How do you call the first element of a dictionary?

Now we have to use dict. keys() method for converting the sequence of keys to a list. Once you will print 'new_k' then the output will display the first key element from the dictionary. In Python, the next() and iter() method is used to get the iterable sequence of dictionary elements.

How do you find the first key-value pair in a dictionary?

In Python, there are a few different ways we can get the first key/value pair of a dictionary. The easiest way is to use the items() function, convert it to a list, and access the first element. If you only care about getting the first value of a dictionary, you can use the dictionary values() function.


1 Answers

Note that to call First here is actually to call a Linq extension of IEnumerable, which is implemented by Dictionary<TKey,TValue>. But for a Dictionary, "first" doesn't have a defined meaning. According to this answer, the last item added ends up being the "First" (in other words, it behaves like a Stack), but that is implementation specific, it's not the guaranteed behavior. In other words, to assume you're going to get any defined item by calling First would be to beg for trouble -- using it should be treated as akin to getting a random item from the Dictionary, as noted by Bobson below. However, sometimes this is useful, as you just need any item from the Dictionary.


Just use the Linq First():

var first = like.First(); string key = first.Key; Dictionary<string,string> val = first.Value; 

Note that using First on a dictionary gives you a KeyValuePair, in this case KeyValuePair<string, Dictionary<string,string>>.


Note also that you could derive a specific meaning from the use of First by combining it with the Linq OrderBy:

var first = like.OrderBy(kvp => kvp.Key).First(); 
like image 92
McGarnagle Avatar answered Sep 19 '22 05:09

McGarnagle