-2

I need help trying to put an inputted string into a dictionary

Input:

Hello my name is Bob Hello Hello

Actual output:

Desired output:

{'Hello' : '1', 'my' : '2', 'name' : '3', 'is' : '4', 'Bob' : '5'} 

Should only record the same word once

My code so far:

    s = input("input sentence: ") 
    file = open("Original.txt", 'w') 
    file.write(s) 
    file.write("\n")
    file.close() 
    num = int(1,2,3,4,5) 
    dictionary = dict(num(s.split()))   
    file = open("Dictionary.txt", 'a') 
    file.write(dictionary) 
    file.close()
    f = open("Dictionary.txt", 'r')
    print(file.read) 
    print(s)
  • 1
    Try this: http://stackoverflow.com/questions/988228/converting-a-string-to-dictionary – Nikita Jun 17 '16 at 14:45
  • 1
    1. What does your code so far do, and how does that differ from your expectations; and 2. what's with the ridiculous comments? – jonrsharpe Jun 17 '16 at 14:47
  • i need it so the number in the dictionary isnt inputted – Blaze Playz Jun 17 '16 at 14:48
  • Output : Traceback (most recent call last): File "C:\Users\Harry\Desktop\Task3.py", line 13, in code() #Runs the code File "C:\Users\Harry\Desktop\Task3.py", line 7, in code dic = dict(sent.split()) ValueError: dictionary update sequence element #0 has length 5; 2 is required – Blaze Playz Jun 17 '16 at 14:50
  • and i just like to comment my work – Blaze Playz Jun 17 '16 at 14:54
  • `num = int(1,2)` is an error, even if it returned a number calling it with `num(sent.split())` is an error, even if that works then `file.write(dict)` is trying to write `` to a file which is an error.... and then `print(f.read)` doesn't read the file but shows the `` representation of the method.... – Tadhg McDonald-Jensen Jun 17 '16 at 18:04

1 Answers1

0

The code below splits a sentence into words and puts them in a dcitionary in the manner that you want.

>>> string = 'Hello my name is bob'
>>> string = {v: k for k ,v in enumerate(string.split(), start=1)}
>>> string
{'bob': 5, 'is': 4, 'my': 2, 'Hello': 1, 'name': 3}
>>> 
tjbadr
  • 18
  • 4
  • No. If the input is `Hello my name is Bob Hello Hello`, this will return `{'Bob': 5, 'Hello': 7, 'is': 4, 'my': 2, 'name': 3}`. Since it will update `"Hello": 1` with `"Hello": 6` first and then with `"Hello": 7`. – emre. Jun 17 '16 at 16:34
  • @emre. that is undefined behaviour based on the OP, it was never specified if the *first* occurrence of the word should be kept. – Tadhg McDonald-Jensen Jun 17 '16 at 18:00
  • @Tadhg McDonald-Jensen OP said the desired output is `{'Hello' : 1, 'my' : 2, 'name' : 3, 'is' : 4, 'Bob' : 5}` yet this returns `{'Hello' : 7, 'my' : 2, 'name' : 3, 'is' : 4, 'Bob' : 5}` which is not the "desired" output. – emre. Jun 20 '16 at 10:59