Harpal Harpal - 8 days ago 5
Python Question

Python: Index a Dictionary?

I have a Dictionary below:

colors = {
"blue" : "5",
"red" : "6",
"yellow" : "8",
}


How do I index the first entry in the dictionary?

colors[0]
will return a
KeyError
for obvious reasons.

Answer

Dictionaries are unordered in Python. If you do not care about the order of the entries and want to access the keys or values by index anyway, you can use d.keys()[i] and d.values()[i] or d.items()[i]. (Note that these methods create a list of all keys, values or items, respectively. So if you need them more then once, store the list in a variable to improve performance.)

If you do care about the order of the entries, starting with Python 2.7 you can use collections.orderdDict. Or use a list of pairs

l = [("blue", "5"), ("red", "6"), ("yellow", "8")]

if you don't need access by key. (Why are your numbers strings by the way?)