user4864703
user4864703

Reputation: 21

Updating dictionary - Python

total=0
line=input()
line = line.upper()

names = {}


(tag,text) = parseLine(line) #initialize

while tag !="</PLAY>":  #test
    if tag =='<SPEAKER>':
        if text not in names:
            names.update({text})

I seem to get this far and then draw a blank.. This is what I'm trying to figure out. When I run it, I get:

ValueError: dictionary update sequence element #0 has length 8; 2 is required

Make an empty dictionary

Which I did. (its keys will be the names of speakers and its values will be how many times s/he spoke)

Within the if statement that checks whether a tag is <SPEAKER>

If the speaker is not in the dictionary, add him to the dictionary with a value of 1

I'm pretty sure I did this right.

If he already is in the dictionary, increment his value

I'm not sure.

Upvotes: 2

Views: 100

Answers (1)

user764357
user764357

Reputation:

You are close, the big issue is on this line:

names.update({text})

You are trying to make a dictionary entry from a string using {text}, python is trying to be helpful and convert the iterable inside the curly brackets into a dictionary entry. Except the string is too long, 8 characters instead of two.

To add a new entry do this instead:

names.update({text:1})

This will set the initial value.


Now, it seems like this is homework, but you've put in a bit of effort already, so while I won't answer the question I'll give you some broad pointers.

Next step is checking if a value already exists in the dictionary. Python dictionaries have a get method that will retrieve a value from the dictionary based on the key. For example:

> names = {'romeo',1}
> print names.get('romeo')
1

But will return None if the key doesn't exist:

> names = {'romeo',1}
> print names.get('juliet')
None

But this takes an optional argument, that returns a different default value

> names = {'romeo',2}
> print names.get('juliet',1)
1

Also note that your loop as it stands will never end, as you only set tag once:

(tag,text) = parseLine(line) #initialize
while tag !="</PLAY>":  #test
    # you need to set tag in here
    # and have an escape clause if you run out of file

The rest is left as an exercise for the reader...

Upvotes: 1

Related Questions