user7222454
user7222454

Reputation: 67

Can someone explain how a dictionary can hold different input values under one key

I have this simple looping code that takes in a line of user input and (after making this into a list) puts the individual words into a dictionary as keys, with the lineCount number being the value. Can someone explain how to adjust this so that if the same word is entered on a different line, it doesn't replace the dictionary value but instead just adds to it?

import string
lineCount = 1
q = raw_input("enter something")
d = {}

while q != "no":
    q = q.split()
    for word in q:
        d[word] = lineCount
    lineCount += 1
    q = raw_input("enter something")

print d

For example, if the input is "x y" on line 1, and "x n" on line 2, the dictionary should print as "x: 1,2 y:1 n:2" but currently it would only print "x:2 y:1 n:2" as the original lineCount value associated with key x is replaced. If possible, please avoid importing collections in the solution, as I would rather understand the longest way possible first. Many thanks in advance.

Upvotes: 0

Views: 65

Answers (3)

ettanany
ettanany

Reputation: 19806

Using lists for your dictionary values, you can have the following solution:

line_count = 1
q = raw_input("enter something: ")
d = {}

while q != "no":
    words = q.split()
    for word in words:
        if word in d and line_count not in d[word]:
            d[word].append(line_count)
        else:
            d[word] = [line_count]
    line_count += 1
    q = raw_input("enter something: ")

print d

Example of output:

>>> python word_lines.py
enter something: hello world
enter something: hello
enter something: world
enter something: sof
enter something: no
{'world': [1, 3], 'hello': [1, 2], 'sof': [4]}

Upvotes: 1

Tobias Mayr
Tobias Mayr

Reputation: 186

If you really want to use a Dictionary instead of a list as suggested by ettanany, I would suggest you use the lines as the keys and the words as values since lines are unique and words are not. I'm sure you can figure this out without a code sample :)

Upvotes: 0

daniboy000
daniboy000

Reputation: 1129

You can use get if a default value like in the code below:

lineCount = 1
q = raw_input("enter something")
d = {}

while q != "no":
    q = q.split()
    for word in q:
        d[word] = d.get(word, 0) + 1
    lineCount += 1
    query = raw_input("enter something")

When you add the word for the first time, the get won't find the word and will return 0 (the default value). So you add this with 1 to update the result.

Upvotes: 1

Related Questions