0

I am new to python so excuse my stupidity. I am trying to iterate over a dictionary that is in a file (.txt). However, I only want to iterate over the keys from the dictionary, not the values. I have been trying for hours but have made no progress. Thanks for the help.

kluizen = {
    11;kaasstengel,
    1;geheim,
    5;kluisvanpietje,
    12;z@terd@g
 } #the number of a locker with the password afterwards.

f = open('fa_kluizen.txt', 'r') 
contents = f.read() 
print(contents) 

for numbers in contents: print(numbers) 
f.close()
4
  • 1
    for key in dictionary: If you iterate over a dictionary, you get the keys. Commented Oct 4, 2020 at 10:19
  • Share your tries (code) and a sample of you file Commented Oct 4, 2020 at 10:19
  • Edit your post when adding more info, not in comment and explain what is what Commented Oct 4, 2020 at 10:23
  • You should use colons in you dictionary not semi-colons. Does the text file you're importing have semi-colons? Commented Oct 4, 2020 at 10:59

2 Answers 2

1

Try this:

import json

with open("path/to/file.txt", "r") as f:
    # read the file as dictionary
    file_as_dict = json.load(f) 

    # iterate over the keys
    for key in file_as_dict:
        print(key)
Sign up to request clarification or add additional context in comments.

Comments

0

That file does not contain a dictionary, as you cannot store literally a Python dictionary in a file.

But I agree with you it looks like a dictionary in the sense that it has information organized in key value pairs.

You're interested in getting the keys out of there: that is the number of the locker.

mykeys = []

with open('fa_kluizen.txt', 'r') as fp:
    for line in fp:
        if ';' in line:
            key, value = line.strip().split(';')

            mykeys.append(key)


# now we have it in mykeys list

for key in mykeys:
    print(key)

Please try this:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.