Python Using an OrderedDict - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Python Using an OrderedDict - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Friday, December 7, 2018

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)

Screenshot 

python order dict

 

No comments:

Post a Comment

Post Top Ad