Словарь Python и сравнение списков - PullRequest
0 голосов
/ 24 октября 2018

Я пытаюсь сравнить каждый элемент в списке «строк» ​​со словарем «dic», а затем добавить элемент из строк в dic, если он не существует, или добавить 1 к значению ключа всловарь.

import string

def uniques():
    file = open("test.txt", "r")
    dic = {}
    data = file.read().replace('\n', ' ')
    strip = removePunctuation(data)
    lines = strip.split(' ')
    print(strip)
    print(lines)

    for item in lines:

        #this produces an error of unhashable type: 'list'
        if lines in dic:
            dic[item] = dic[item] + 1
        else:
            print("else ran")
            dic[item] = 1

    for item in dic:
        print(item, dic[item])
        print("There are " + str(len(dic)) + " items in the dictionary")

def removePunctuation(text):
    text = text.strip()
    return text.rstrip(string.punctuation)

uniques()

Ответы [ 2 ]

0 голосов
/ 24 октября 2018

его

if item in dic:
      dic[item] = dic[item] + 1

вместо

if lines in dic:
      dic[item] = dic[item] + 1
0 голосов
/ 24 октября 2018
if item in dic.values():

вместо if lines in dic:

Это создаст список dict_value.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...