1

I have a dictionary in a text file in exact format given bellow,

 {'one': 'a', 'two': 'b', 'three': 'c'}

I want to take that dictionary in a variable say dict1. My program generates new key value pairs, if the new generated key is is not present in dict1 then I want to add this new key in dict1. finally I want to update txt file with this updated dictionary.

I know how to add key value pairs to a dict but I am not able to read that dictionary from txt file into a dictionary type of variable.

can anybody help plz ?

8
  • something like stackoverflow.com/questions/3277503/… is how to read a text file Commented Dec 17, 2015 at 17:29
  • "I am not able to read that dictionary from txt file into a dictionary type of variable" <- why, what's the problem? Commented Dec 17, 2015 at 17:35
  • Here's a hint: use ast.literal_eval. Commented Dec 17, 2015 at 17:37
  • alternatively, store and load as json. Commented Dec 17, 2015 at 17:39
  • How was this file written in the first place? You need to know the rules used for serialization before you can figure out how to parse it again. Commented Dec 17, 2015 at 17:43

2 Answers 2

2

This piece of code works for me:

import ast

dict_file = open("dict.txt", "r")
dict_string = dict_file.readline().strip()
dict_file.close()

d = ast.literal_eval(dict_string)
print d["one"]

#change your dictionary e.g:
d["foo"] = "bar"

f = open("dict.txt", "w")
f.write(str(d))
f.close()

It simply reads the string from the file and creates a dictionary using the "ast.literal_eval". You can then commit changes to the dictionary, convert it to a string and write it to the txt file.

You could alternatively use Pickle

Sign up to request clarification or add additional context in comments.

2 Comments

after I have updated the dict how to store updated dict to that dict.txt file?
@Ritzor I have updated the answer
1

If your text file is named foo.txt, then

import json

with open('foo.txt', 'r') as f:
    d = json.load(f)

new_key = 'foo'
if new_key not in d:
    d[new_key] = 'bar'
    with open('foo.txt', 'w') as f:
        json.dump(d, f)

2 Comments

If his file is formatted as he's shown, your code's going to throw an exception because of the single quotes. He'll need " everywhere to make it JSON-compatible.
OP didn't show us JSON so this can't really be considered an answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.