1
word = 'pythonist'

#splitting word into its alphabets
newword = []
for char in word:
    newword.append(char)

print newword

##########################

#creating the dict

d = {}
length = len(word)


for x in range(0,length):
    d["{0}".format(x)] = newword[x]

print d

If you notice the dictionary key:value is not in the same order the letters in the string 'pythonist'. What is causing this behaviour? Im thinking, it's something to do with the way the dictionary is created because im letting the values for the dict be taken from a list I just created?

kalin
  • 155
  • 9
  • 3
    Dictionaries are unordered. If want to maintain order you should be using an `OrderedDict` from the `collections` module. https://docs.python.org/2/library/collections.html#collections.OrderedDict – kylieCatt Nov 01 '14 at 23:29
  • Tip - You could replace ```"{0}".format(x)``` with ```str(x)``` – wwii Nov 01 '14 at 23:38

3 Answers3

1

Dictionaries in python are implemented as HashTables which are unordered containers. OrderedDict will retain the order.

You can read about OrderedDict here: OrderedDict

Foggzie
  • 9,691
  • 1
  • 31
  • 48
0

Python's dictionaries are unsorted as a design decision. Your dictionary is created correctly it is only that the information about order is lost.

k-nut
  • 3,447
  • 2
  • 18
  • 28
0

Your code can be simplified quite a bit:

from collections import OrderedDict

word = 'pythonist'

d = OrderedDict()
for x, c in enumerate(word):
    d["{0}".format(x)] = c

print d

This code produces the output:

OrderedDict([('0', 'p'), ('1', 'y'), ('2', 't'), ('3', 'h'), ('4', 'o'), ('5', 'n'), ('6', 'i'), ('7', 's'), ('8', 't')])

As you can see, courtesy of OrderedDict, the output is in order.

Notes

  • There is no need to split word into newword. In python, strings are themselves iterables.

  • In computer programming, the need for constructions like this appears often:

    for x in range(0,length):
        d["{0}".format(x)] = newword[x]
    

    For this reason, python created enumerate which gives you both x, and newword[x] at the same time.

  • The documentation for OrderedDict is here. For reasons of speed, conventional python dictionaries are unordered. When this is not satisfactory, use the class OrderedDict.

John1024
  • 109,961
  • 14
  • 137
  • 171
  • Thanks for the enumerate tip John! I'm splitting word into newword because the problem im trying to solve eventually requires(atleast I think it does) a rearrangement of letters. – kalin Nov 01 '14 at 23:41