I have a snippet of code which orders a dictionary alphabetically. Is there a way to select the ith key in the ordered dictionary and return its corresponding value? i.e.
import collections
initial = dict(a=1, b=2, c=2, d=1, e=3)
ordered_dict = collections.OrderedDict(sorted(initial.items(), key=lambda t: t[0]))
print(ordered_dict)
OrderedDict([('a', 1), ('b', 2), ('c', 2), ('d', 1), ('e', 3)])
I want to have some function along the vein of...
select = int(input("Input dictionary index"))
#User inputs 2
#Program looks up the 2nd entry in ordered_dict (c in this case)
#And then returns the value of c (2 in this case)
How can this be achieved? Thanks.
(Similar to Accessing Items In a ordereddict, but I only want to output the value of the key-value pair.)
You can use the itertools. islice function, which takes an iterable and outputs the stop first elements. This is beneficial since iterables don't support the common slicing method, and you won't need to create the whole items list from the OrderedDict.
By the first key, we mean the key saved in the first index of the dictionary. In Python versions 3.7 and above, where a dictionary is ordered, we can get the first key, by first converting the dictionary into an iterated object using iter() function and then fetching its first index key using the next function.
The OrderedDict is a subclass of dict object in Python. The only difference between OrderedDict and dict is that, in OrderedDict, it maintains the orders of keys as inserted. In the dict, the ordering may or may not be happen. The OrderedDict is a standard library class, which is located in the collections module.
The OrderedDict() is a method of the collections module that returns an instance of a dict subclass with a method specialized for rearranging dictionary order. The sorted() function returns a sorted list of the specified iterable object. The OrderedDict() method preserves the order in which the keys are inserted.
In Python 2:
If you want to access the key:
>>> ordered_dict = OrderedDict([('a', 1), ('b', 2), ('c', 2), ('d', 1), ('e', 3)])
>>> ordered_dict.keys()[2]
'c'
If want to access the value:
>>> ordered_dict.values()[2]
2
If you're using Python 3, you can convert the KeysView
object returned by the keys
method by wrapping it as a list:
>>> list(ordered_dict.keys())[2]
'c'
>>> list(ordered_dict.values())[2]
2
Not the prettiest solution, but it works.
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