2016-05-29 9 views
1

どうすれば修正できますか?syntax_error:辞書の更新

# E.g. word_count("I am that I am") gets back a dictionary like: 
# {'i': 2, 'am': 2, 'that': 1} 
# Lowercase the string to make it easier. 
# Using .split() on the sentence will give you a list of words. 
# In a for loop of that list, you'll have a word that you can 
# check for inclusion in the dict (with "if word in dict"-style syntax). 
# Or add it to the dict with something like word_dict[word] = 1. 
def word_count(string): 
    word_list = string.split() 
    word_dict = {} 
    for word in word_list: 
     if word in word_dict: 
      word_dict.update(word:word_dict(word)+1) 
     else: 
      word_dict[word]=1 
    return word_dict 

enter image description here

免責事項:辞書内のキーを更新するにはPython

答えて

2

の総初心者、ちょうど[...]サブスクリプションの構文を使用して、キーに割り当てます。

word_dict[word] = word_dict[word] + 1 

あるいは

word_dict[word] += 1 

あなたの試みは、2つの理由のために、有効な構文ではありません。

  • word_dict.update()は、(...)呼び出し構文内のすべてが有効な式でなければならないメソッド呼び出しです。 key: valueはスタンドアローン式ではなく、{key: value}辞書表示内でのみ有効です。 word_dict.update()は、辞書オブジェクト、または(key, value)ペアのシーケンスのいずれかをとります。
  • word_dict(word)を呼び出すと、wordの値を取得しようとするよりも、辞書が呼び出されます。それは別の辞書やシーケンスを作成する必要があるため、単にキーを更新するword_dict.update()を使用し

は、少しやり過ぎです。どちらか次のいずれかが動作します:

word_dict.update({word: word_dict[word] + 1}) 

やPythonの標準ライブラリは、単語をカウントするためのよりよい解決策が付属していることを

word_dict.update([(word, word_dict[word] + 1)]) 

注:collections.Counter() class

from collections import Counter 

def word_count(string): 
    return Counter(string.split()) 

Counter()dictのサブクラスです。

+0

.update()を使用してその行を書く方法を教えてください。お返事ありがとうございます:) –

+0

インタビュアーが 'コレクションからインポートを使用する場合Counter def word_count(string): return counter(string.split())'は受け入れ可能ですか?面接で受け入れられる言語のレベルはどの程度ですか?ヒントをありがとう –

+1

@MonaJalal:標準ライブラリに精通していることを示しています。私は 'Counter()'のすべての機能を知っているかどうかをさらに調べ、おそらくそれを使って何ができるか質問したり、Counter()を使わずに同じことをする方法プローブの基本的なPythonの知識。それはあなたがインタビューしているポジションによって異なります。 –

1

dict.updateを使用して実装できます。ここにあなたの問題word_dict.update({word:word_dict(word)+1})にこのword_dict.update(word:word_dict(word)+1)のようにコードを変更するためにdict.update

In [74]: test_dict = {1:'apple',2:'grapes'} 
In [75]: test_dict.update({3:'orange'}) 
In [76]: test_dict 
Out[76]: {1: 'apple', 2: 'test', 3: 'orange'} 

ための一例です。

ここにはreferenceがあります。