Reputation: 405
I am using pickle to dump a dictionary object into a txt file. I need to grab the dictionary from the file and extract only certain values and put them inside of an object as a string.
My dictionary looks something like this:
obj_dict = { 'name': 'MYID', 'value': 'usdf23444',
'name': 'MYID2', 'value' : 'asdfh3479' }
Part of the dilemma I have is that there are two 'name'
and two 'value'
in the dictionary and I need to grab each separately.
Here is the code I am using:
import pickle
filepath = file.txt
output = open(filepath, 'rb')
obj_dict = pickle.load(output)
for i in obj_dict:
NewString = "VALUE1=" + i['value1'] + "VALUE2=" + i['value2']
print(NewString)
I know this code doesn't work, I'm more showing what I need my end result to look like but basically I need each value to be put into a string that I can use later. How can I reference 'value1'
and 'value2
' correctly? Also I am getting this error when trying to just get one 'value':
TypeError: list indices must be integers or slices, not str
EDIT FOR COMMENT 2
I'm not sure if that's true, I can run this code:
output = open(filepath, 'rb')
obj_dict = pickle.load(output)
for i in obj_dict:
print(i['value'])
and my output is:
usdf23444
asdfh3479
Upvotes: 0
Views: 758
Reputation: 2917
After the update, it looks like it is a list of dicts. Try:
strings = ["VALUE{}={}".format(i, d['value']) for i, d in enumerate(obj_dict)]
Upvotes: 1