how to keep order key in a dictionary

A

azrael

I 'm currenty working on a project for which it would be great to use
a dictionary. At the begining I have a list of strings that should
represent the keys in the dictionary. When I try to create a
dictionary it rearanges the keys. For this dictionary it is realy
important to keep the right order. Is it possible to arange them in a
specific order?
 
B

BartlebyScrivener

For this dictionary it is realy
important to keep the right order. Is it possible to arange them in a
specific order?

Not sure what order you want, but how about sorting the keys?

def printdict(dict):
"""print sorted key:value pairs"""
keys = dict.keys()
keys.sort()
for key in keys:
print key, ":", dict[key]

from Python Visual Quickstart, Chris Fehily p. 157
 
B

Bruno Desthuilliers

azrael a écrit :
I 'm currenty working on a project for which it would be great to use
a dictionary. At the begining I have a list of strings that should
represent the keys in the dictionary. When I try to create a
dictionary it rearanges the keys. For this dictionary it is realy
important to keep the right order. Is it possible to arange them in a
specific order?
No (not with the builtin dict type at least). You have to keep the order
by yourself. The nice thing is that you already have this : your list of
strings. Then you just have to iterate over this list and get to the dict:

for key in list_of_strings:
print dic[key]

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top