-1

Hello i want to print this dictionary in order but i dont know how:

s = input("")
slist = s.split()
finaldict = {}
for word in slist:
    if not finaldict.get(word):
        finaldict[word] = slist.count(word)

for palabra in finaldict:
    finaldict[palabra]=str(finaldict[palabra])
    print(palabra,finaldict[palabra])

input : this is a test a test a test expected output:

this 1
is 1
a 3
test 3

i want that order but i get random order prints

Thanks!

2 Answers2

1

You can't really have an order in a dictionary. Look at the OrderedDict module to print things in the order you store them

import collections 
s = input("")
slist = s.split()
finaldict = collections.OrderedDict()
for word in slist:
    if not finaldict.get(word):
        finaldict[word] = slist.count(word)

for palabra in finaldict:
    finaldict[palabra]=str(finaldict[palabra])
    print(palabra,finaldict[palabra])
rma
  • 1,853
  • 1
  • 22
  • 42
0

Dictionaries by their nature are unordered. You want to use an OrderedDict (found in the collections module). You would assign to an OrderedDict in the same way you would a regular dict, and initialize it by passing a list of 2-tuples to the OrderedDict constructor. For example:

>>> from collections import OrderedDict
>>> spam = OrderedDict([('a', 1), ('b', 2)])
>>> spam['c'] = 3
>>> print spam
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
>>> eggs = OrderedDict()
>>> eggs['a'] = 1
>>> print eggs
OrderedDict([('a', 1)])
train1855
  • 300
  • 2
  • 5
  • 14