I would like to get the value by key index from a Python dictionary. Is there a way to get it something like this?
dic = {} value_at_index = dic.ElementAt(index)
where index
is an integer
Python dictionary index of key By using list(*args) with a dictionary it will return a collection of the keys. We can easily use the index to access the required key from the method and convert it to a list. In this example to use the list[index] function and it will return the key at index in the list.
You can find a dict index by counting into the dict. keys() with a loop. If you use the enumerate() function, it will generate the index values automatically.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
In Python versions before 3.7 dictionaries were inherently unordered, so what you're asking to do doesn't really make sense.
If you really, really know what you're doing, use
value_at_index = list(dic.values())[index]
Bear in mind that prior to Python 3.7 adding or removing an element can potentially change the index of every other element.
Let us take an example of dictionary:
numbers = {'first':0, 'second':1, 'third':3}
When I did
numbers.values()[index]
I got an error:'dict_values' object does not support indexing
When I did
numbers.itervalues()
to iterate and extract the values it is also giving an error:'dict' object has no attribute 'iteritems'
Hence I came up with new way of accessing dictionary elements by index just by converting them to tuples.
tuple(numbers.items())[key_index][value_index]
for example:
tuple(numbers.items())[0][0] gives 'first'
if u want to edit the values or sort the values the tuple object does not allow the item assignment. In this case you can use
list(list(numbers.items())[index])
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