python - How to index into a dictionary? -


i have dictionary below:

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

how index first entry in dictionary?

colors[0] return keyerror obvious reasons.

dictionaries unordered in python. if not care order of entries , want access keys or values index anyway, can use d.keys()[i] , d.values()[i] or d.items()[i]. (note these methods create list of keys, values or items, respectively. if need them more once, store list in variable improve performance.)

if care order of entries, starting python 2.7 can use collections.ordereddict. or use list of pairs

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

if don't need access key. (why numbers strings way?)


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -