0

I have a file with the following format.

>abc
qqqwqwqwewrrefee
eededededededded
dededededededd
>bcd
swswswswswswswws
wswswsddewewewew
wrwwewedsddfrrfe
>fgv
wewewewewewewewew
wewewewewewewxxee
wwewewewe

I was trying to create a dictionary with (>abc,>bcd,>fgv) as keys and the string below them as values. I could extract the keys but confused about updating the values. help me pls.

file2 = open("ref.txt",'r')
for line in file2.readlines():
    if ">" in line:
    print (line)

4 Answers 4

3

Not sure what you mean about "updating" the values, but try this:

mydict=[]
with open("ref.txt", "r") as file2:
    current = None
    for line in file2.readlines():
        if line[0] == ">":
            current = line[1:-1]
            mydict[current] = ""
        elif current:
            mydict[current] += line # use line[:-1] if you don't want the '\n'

In [2]: mydict
Out[2]: {'abc': 'qqqwqwqwewrrefee\neededededededded\ndededededededd\n',
         'bcd': 'swswswswswswswws\nwswswsddewewewew\nwrwewedsddfrrfe\n',
         'fgv': 'wewewewewewewewew\nwewewewewewewxxee\nwwewewewe\n'}
Sign up to request clarification or add additional context in comments.

2 Comments

The value is complete string, not list. I mean key is abc and value is whole string(the characters below it)
your key(current variable) contains "\n"
1

When you get a line value with the '>' in it, save the line in a variable. When you read a line without the '>' in it, add it to a dictionary entry keyed by the previously saved variable.

key = None
dict = {}
for line in file2.readlines():
    if ">" in line:
        key = line
        dict[key] = ''  # Initialise dictionary entry
    elif key is not None:
        dict[key] += line  # Append to dictionary entry

Comments

1
dictionary = {}
with open("file.txt","r") as r:
    for line in r.readlines():
        if ">" in line:
            key = line[1:].strip()
            dictionary[key] = ""
        else:
            dictionary[key] += line

print(dictionary)

Comments

0
d={}
key=''
file2 = open("ref.txt",'r')
for line in file2.readlines():
    if line.startswith('>'):
        key=line.strip()
        d[key]=[]
        continue
    d[key].append(line.strip())
file.close()

I have not tested the above code, but it should work

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.