-1

I'm trying write a function that reads the words contained in the .txt file and writes them as keys in the dictionary. The value can be any. The program should allow me to use the in operator to check if the string is in the dictionary.

I tried something like this:

words = open('words.txt')
def k():
    for word in words:
        key = word[0]

print(k)

I have no idea how to do it. anyone could help me?

  • What should be the values for those keys? – Austin Nov 17 '19 at 10:47
  • A `dictionary` without `value`s in `python` is called a `set`. You can create it easily with: `words_set = set(words)` – Aryerez Nov 17 '19 at 10:49
  • 1
    Dictionaries aren't just keys, they contain pairs of keys and values, can you edit your question to give an example of the expected output? – Ofer Sadan Nov 17 '19 at 10:50
  • The value can be any – KBoardSurfer Nov 17 '19 at 10:51
  • 1
    Also, the code you provided shows you probably don't know how to call functions, how to return values from functions, how to read files, and what exactly are dictionaries. I strongly suggest going back to the basics of python – Ofer Sadan Nov 17 '19 at 10:52

6 Answers6

0

The variable word is your word in fact. It is not necessary to put the index 0.

words = open('words.txt')
def k():
    keys = []
    for word in words:
        keys.append(word)
    return keys
sbarboza
  • 72
  • 1
  • 8
0

I think you want to read a file and iterate over its lines and save the first word of each line. The with open syntax is better than directly opening a file because of this reasons.Try this code:

with open('words.txt') as f:
  words=f.read()
  keys=[]
  for word in words:
    keys.append(word[0])
  print(keys)
Pratik
  • 1,351
  • 1
  • 20
  • 37
0

You can do something like this:

dict_ = {}
with open("test.txt") as f:
    key = [line.split() for line in f]
key = key[0]
print(key)
dict_ = dict((k,'any') for k in key)
print(dict_)

This gives you:

['HI', 'This', 'IS', 'A', 'TEST']
{'HI': 'any', 'This': 'any', 'IS': 'any', 'A': 'any', 'TEST': 'any'}

When the text file contained

HI This IS A TEST
SSharma
  • 951
  • 6
  • 15
0
with open('words.txt') as f:
  words = f.read()
  keys = set(words)

if "apple" in keys:
  pass

if "orange" in keys:
  pass

if "pear" in keys:
  pass
David Callanan
  • 5,601
  • 7
  • 63
  • 105
0

file=open("C:/Users/sghungurde/Documents/love.txt")

def k():

    dict={}

    for word in file.read().split():

        key=word

    #print(word)

        dict[key]='null'

    return dict


print(k())
SRG
  • 345
  • 1
  • 9
0

assigning keys as set elements as set elements can't be duplicated

set1= {ele for ele in  file.read().split()}

print(set1)
SRG
  • 345
  • 1
  • 9