Python Using an OrderedDict

Python Using an OrderedDict

Using an OrderedDict

Standard Python dictionaries don't keep track of the order in which keys and values are added; they only preserve the association between each key and its value. If you want to preserve the order in which keys and values are added, use an OrderedDict.

#Preserving the order of keys and values
from collections import OrderedDict

#store each person's languages, keeping
#track of who responded first.
fav_languages = OrderedDict()

fav_languages['jen'] = ['python', 'ruby']
fav_languages['sarah'] = ['c']
fav_languages['edward'] = ['ruby', 'go']
fav_languages['phil'] = ['python', 'haskell']

# Display the results, in the same order they 
# were entered.
for name, langs in fav_languages.items():
 print(name + ":")
 for lang in langs:
  print("-" + lang)


python order dict



Post a Comment