Python Dictionary

I’m know some of Python, but I need some help. Is there a way to get a position of some element in a dictionary?


MyDict = {‘first’:1,‘second’:2,‘third’:3}

Element ‘second’ is on a secod place in that dict, so is there a way to get that place, something like MyDict.indexOf(‘second’) that would return 2, or i will have to write a function that will go through a whole dict and find that pos by my self?

When you create a dictionary, you are not garantueed that you get the order of items you created it with, so doing something like .indexOf() is not smart.

When I run an iteration on your dictionary I get:

>>> MyDict = {‘first’:1,‘second’:2,‘third’:3}
>>> for k,v in MyDict.iteritems():
… print k,v

second 2
third 3
first 1


Yes dictionaries/associative arrays have an undefined order, since they can be accessed by an immutable key, as opposed to a list which requires contiguous integer indicies.

If you need the position of an element in a dictionary then you are using the wrong data type/structure.

Thanks guys for the tip. I have suspected that I would need to use lists instead of a dict, but I’ve had to ask :slight_smile:

you could use dictionary like this:

MyDict = {1:“apples”,2:“bananas”,3:“grapes”}
while count<100:
>>if MyDict.has_key(count):
>>>>print "Item ",i,MyDict(count)
>>i = i+1

note: >> is a tab

MyDict = {1:"apples",2:"bananas",3:"grapes"}
 while count&lt;100:
 &gt;&gt;if MyDict.has_key(count):
 &gt;&gt;&gt;&gt;print "Item ",i,MyDict(count)
 &gt;&gt;i = i+1

Err, that’s an infinite loop, and MyDict(count) is invalid syntax

MyDict = {1:"apples",2:"bananas",3:"grapes"}
for a in MyDict:
    print 'Item:-%s=  %s' %(a,MyDict[a])

Isn’t infinite and would produce the same output (if the original worked).