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?
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.
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.
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.
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();
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