Reputation: 97
I have a list of pairs like pair_users = [('a','b'), ('a','c'), ('e','d'), ('e','f')]
when I saved this I used this code:
with open('pair_users.txt', 'w') as f:
f.write(','.join('%s' % (x,) for x in pair_users))
Then, when I want to use it in another notebook to create a dictionary which will look like this {'a': ['b', 'c'], 'b': [], 'c': [], 'd': [], 'e': ['d', 'f'], 'f': []}
to create that dictionary I am using this code:
graph = {}
for k, v in pair_users:
graph.setdefault(v, [])
graph.setdefault(k, []).append(v)
graph
but my problem is when I run the graph code after opening the file I saved pair_users = open('/content/pair_users.txt', 'r')
the result I get is an empty dictionary {}
.
This is the output I have when I open the file
When I use the code to create the graph without saving the list as txt file I get the right answer, my problem is when I save it and then I open it.
Here it worked for example:
Thanks in advance for your ideas!
Upvotes: 0
Views: 102
Reputation: 14228
The result you get when you read the file is just a single string. You cannot iterate the string as k,v
.
You could either parse the string into tuples by your own parsing or you could go with an option like pickle
.
With pickle it is :
import pickle
with open('pair_users.pkl', 'wb') as f:
pickle.dump(pair_users, f)
f.close()
with open('pair_users.pkl', 'rb') as f:
pair_tuple = pickle.load(f)
f.close()
print(pair_tuple)
Upvotes: 1
Reputation: 62373
pair_users
is a str
type when it's read back in.ast.literal_eval
to convert the string
to a tuple
.from ast import literal_eval
pair_users = open('test.txt', 'r')
pair_users= literal_eval(pair_users.read())
graph = {}
for k, v in pair_users:
graph.setdefault(v, [])
graph.setdefault(k, []).append(v)
graph
[out]:
{'b': [], 'a': ['b', 'c'], 'c': [], 'd': [], 'e': ['d', 'f'], 'f': []}
Upvotes: 1
Reputation: 1691
Apart from using pickle
or parsing the string as proposed in the other answeres, you can use some "more universal format", e.g. JSON:
import json
pair_users = [('a','b'), ('a','c'), ('e','d'), ('e','f')]
with open('pair_users.txt', 'w') as f:
json.dump(pair_users,f)
with open("pair_users.txt") as f:
pair_users = json.load(f)
graph = {}
for k, v in pair_users:
graph.setdefault(v, [])
graph.setdefault(k, []).append(v)
print(graph)
Upvotes: 1