Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing dictionary value by index in python [duplicate]

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

like image 996
Dmitry Dyachkov Avatar asked Feb 27 '13 14:02

Dmitry Dyachkov


People also ask

Can we use index in dictionary Python?

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.

How do you access an index from a dictionary?

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.

Does dictionary allow duplicate values?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

Does dictionary allow duplicate values in Python?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.


2 Answers

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.

like image 140
NPE Avatar answered Sep 20 '22 13:09

NPE


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]) 
like image 34
mohammed ali shaik Avatar answered Sep 21 '22 13:09

mohammed ali shaik