0

Is it possible to retrieve the items of the default dict, in python, in the same way it was inserted. Below is the snippet of the code.

value = "Examplexa"
od = defaultdict(int)
for i in value:
   od[i] = od[i] + 1

print(od)

The above code does the purpose in counting the number of each characters in the string. However, in the output, an unordered dict is displaying. I knew that ordered dict can be used to retrieve the items in the same way it was inserted. but, i am just curious to understand is there a way to arrange output of default dict in a ordered way. Please advise.

Sayanthan
  • 67
  • 1
  • 1
  • 7
  • 1
    What Python version are you running? For Python >= 3.6, you should get the output according to the insertion order . – revliscano Jul 29 '20 at 15:51
  • The point of having a dictionary is that the order in which the data has been entered does not matter. It works with keys. Having said so, you can implement the `DefaultOrderedDict` as suggested in https://stackoverflow.com/questions/6190331/how-to-implement-an-ordered-default-dict – David Duran Jul 29 '20 at 15:56
  • Does this answer your question? [Are dictionaries ordered in Python 3.6+?](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6) – Ente Jul 29 '20 at 16:04
  • Yes, it works well in Python 3.8. Thanks for the assistance :) – Sayanthan Jul 30 '20 at 07:41

1 Answers1

0

https://docs.python.org/3/whatsnew/3.6.html#new-dict-implementation

maybe this can help.

python3.7
Python 3.7.3 (default, Apr  3 2019, 19:16:38) 
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import defaultdict 
>>> d = defaultdict(int)
>>> for i in 'Examplexa':
...    d[i] = d[i] + 1 
>>> d
defaultdict(<class 'int'>, {'E': 1, 'x': 2, 'a': 2, 'm': 1, 'p': 1, 'l': 1, 'e': 1})