I have a dictionary of keys and values, for example:
{
fred: 1,
dave: 2,
lily: 3
}
How do I get the 2nd element in the dictionary - {dave:2}
in this case?
Background: I've seen this question asked so many times on SO in one form or another, so I thought I'd write a Q&A page as a community wiki that folks can be referred to and which might hopefully become the canonical answer for this question.
This Q&A applies to dictionaries as they are implemented in many different
languages. Different languages use different names to refer to what is
essentially the same data structure - for example they're called hashes in
Perl, dictionaries in Python. In Objective-C they're instances of the
NSDictionary
or NSMutableDictionary
classes.
In a nutshell, you can't - because dictionaries are unordered collections of key/value pairs. The order in which you populate a dictionary is not retained in memory. Here's a simple example in Python:
>>> dict = { 'a': 1, 'b': 2, 'c': 3 }
>>> dict # show the value of dict in memory
{'a': 1, 'c': 3, 'b': 2}
As you can see, although the dictionary is initialised with keys in the order a, b, c, printing the value of the dictionary shows them ordered a, c, b. Even that ordering is not retained in memory; as you add more key/value pairs to a dictionary the ordering in the above expression will continue to change.
Dictionaries are optimised for fast storage and retrieval of a value based on a unique key. The implementation varies from one language to the next but typically it works something like this:
I am newbie here, so can not add a comment yet.....But this is actually a comment to the above answer by Simon.
Useful Question & Nice Answer, Simon. You could have added another section to the answer, saying, Hence, the only way this question makes sense is, if we take an approach like the following examples
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