-1

I was trying to learn about using dictionaries in python and made two very short programs. I have a doubt over the output of the program. Here is the code.

d = {}
d[0] = '0'
d[1] = '1'
d[2] = '2'
for keys in d:
   print d[keys]

and it gave the following output

0
1
2

but, when I made the following program.

d = {}
d['name'] = "Pratik"
d['age'] = 17
d['country'] = "India"
for keys in d:
    print d[keys]

it gave the following output

India
17
Pratik

It would be great if somebody could explain this output to me. The expected output looking at the first output was

Pratik
17
India
Bonifacio2
  • 3,405
  • 6
  • 34
  • 54
Pratik Singhal
  • 6,283
  • 10
  • 55
  • 97

3 Answers3

2

It would be great if somebody could explain this output to me. The expected output looking at the first output was

Dictionaries are not ordered, they are simple hash tables.

Emil Davtyan
  • 13,808
  • 5
  • 44
  • 66
2

Emil gave you the explanation; to expand on that - dictionaries are arbitrarily ordered this means that there is an order, just not one you can rely on (or one that makes sense, like in your case a numeric order).

To fetch items from a dictionary in an order, use an OrderedDict, or create a list of the keys in the order you want them to be fetched, and then step over the list. Lists (and tuples) preserve their order.

k = ['name', 'age', 'country']

for i in k:
   d[i]
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
1

As suggest by @Burhan Khalid you can use ordered dictionary, a fast example:

from collections import OrderedDict

d = OrderedDict()
d['name'] = "Pratik"
d['age'] = 17
d['country'] = "India"

print d

OrderedDict([('name', 'Pratik'), ('age', 17), ('country', 'India')])

you can read more here

Kobi K
  • 7,743
  • 6
  • 42
  • 86