0

I can't see a pattern for the results that I'm having on the print. And I've already tried other solutions for this, but can't get it right =(

s = "hi hi hi, how are you? you you"

print(s)
s = s.replace('?','')
s = s.replace('!','')
s = s.replace(',','')
s = s.replace('.','')

l = s.split()

d = {}

for i, termo in enumerate(l):
    if not d.get(termo):
        d[termo] = []
    d[termo].append(i+1)

print ('d:', d)

An example output:

d: {'you': [6, 7, 8], 'how': [4], 'are': [5], 'hi': [1, 2, 3]}

d: {'are': [5], 'hi': [1, 2, 3], 'how': [4], 'you': [6, 7, 8]}
James
  • 2,843
  • 1
  • 14
  • 24
  • 3
    Dictionaries are inherently unordered. Use `collections.OrderedDict`. – Łukasz Rogalski Aug 01 '16 at 16:00
  • What is your goal? Is that output your expected output or desired ouput? – James Aug 01 '16 at 16:00
  • 2
    Please read http://stackoverflow.com/questions/15479928/why-is-the-order-in-python-dictionaries-and-sets-arbitrary – cdarke Aug 01 '16 at 16:01
  • My goal is the output containing the words in order and the positions that it occurs. d: {'hi': [1.2.3], 'how': [4], 'are': [5], 'you': [6,7,8]} –  Aug 01 '16 at 16:27
  • Possible duplicate of [Python dictionary, keep keys/values in same order as declared](http://stackoverflow.com/questions/1867861/python-dictionary-keep-keys-values-in-same-order-as-declared) – juanpa.arrivillaga Aug 01 '16 at 16:39
  • Possible duplicate of [How can I sort a dictionary by key?](http://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) – David Zemens Aug 01 '16 at 16:40
  • You obviously won't be able to reconstruct the original string, since those punctuation symbols (comma, question mark and exclamation mark), are not represented in the dictionary in any manner. – barak manos Aug 01 '16 at 16:49
  • How about putting the replaces after reconstructing the string? –  Aug 01 '16 at 16:51

1 Answers1

0

A Dictionary is an unordered collection. Use a collections.OrderedDict, instead:

from collections import OrderedDict

s = "hi hi hi, how are you? you you"
s = s.translate(None, '?!,.')
l = s.split()

d = OrderedDict()
for i, termo in enumerate(l):
    d.setdefault(termo, []).append(i)

print ('d:', d)

Notes:

  • collectins.OrderedDict remembers the order in which data are added. Subsequently iteration of the dictionary occurs in the same order.

  • str.translate() is a quick way to delete a class of characters from a string.

  • dict.setdefault() returns a value of a dictionary if the key exists, or creates the value otherwise. It replaces the if x not in d: d[x] = y pattern.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Rob, thank you so much! =) that was exactly what I needed, I understand it now! –  Aug 02 '16 at 00:49