0

Example dictionary:

dictionary = {}
dictionary['a'] = 1
dictionary['b'] = 2
dictionary['c'] = 3
dictionary['d'] = 4
dictionary['e'] = 5
print(dictionary)

run this code 1st time:

{'c': 3, 'd': 4, 'e': 5, 'a': 1, 'b': 2}

2nd:

{'e': 5, 'a': 1, 'b': 2, 'd': 4, 'c': 3}

3rd:

{'d': 4, 'a': 1, 'b': 2, 'e': 5, 'c': 3}

My expected result:

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

or if my code is:

dictionary = {}
dictionary['r'] = 150
dictionary['j'] = 240
dictionary['k'] = 98
dictionary['l'] = 42
dictionary['m'] = 57
print(dictionary)
#The result should be
{'r': 150, 'j': 240, 'k': 98, 'l': 42, 'm': 57}

Because of my project the dictionary with 100++ lists will write to a file and it will easier to read.

P.S. sorry for my english and if my question title is not clear.

Thank you.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
YONG BAGJNS
  • 501
  • 2
  • 8
  • 21

2 Answers2

3

Python's dict are unordered in nature. For maintaining the order in which elements are inserted, use collection.OrderedDict().

Sample Run:

>>> from collections import OrderedDict

>>> dictionary = OrderedDict()
>>> dictionary['a'] = 1
>>> dictionary['b'] = 2
>>> dictionary['c'] = 3
>>> dictionary['d'] = 4
>>> dictionary['e'] = 5

# first print
>>> print(dictionary)
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])

# second print, same result
>>> print(dictionary)
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])

For writing it to the json file, you can dump the dict object to string using json.dumps() as:

>>> import json

>>> json.dumps(dictionary)  # returns JSON string
'{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}' 

As per the collections.OrderedDict() document:

Return an instance of a dict subclass, supporting the usual dict methods. An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • but if he want to print that to file at the end don't you think it will not be very useful, as it's an object not a convetional dictionary that would print out **JSON** structure when printed to file. – harshil9968 Nov 09 '16 at 19:17
  • 1
    @harshil9968: In that case, use `json.dumps()`. Updated answer – Moinuddin Quadri Nov 09 '16 at 19:22
1

Read up on OrderedDict.

https://docs.python.org/2/library/collections.html#collections.OrderedDict

It remembers the insertion order of the keys.

KVISH
  • 12,923
  • 17
  • 86
  • 162