I'm working with a file right now where every line of data is sorted like " Dog 15 28 0 58 79 01" and I'm trying to convert it to a dictionary where Dog is the key and the others are the values.
Because its not split by comma's I've figured out that I should probably .split it to convert it to a list then use a for each loop to set the values in the dictionary but i'm struggling with the execution. This is all in python by the way. How might I go about doing it?
CodePudding user response:
Here is an example of how to split a line and add it to a dictionary :
data = "Dog 15 28 0 58 79 01"
theDict = {}
key = data.split(" ")[0]
values = data.split(" ")[1:]
theDict[key] = values
I hope it help you.
CodePudding user response:
You can't have multiple values for a single a key. There is always a key-value pair. A single key can only have a single value.
Edit: According to the comment, you can do it like this
data = "Dog 15 28 0 58 79 01"
d = {}
d[data.split(" ")[0]] = data.split(" ")[1:]
Edit: For every line in the file you can do it like
l = []
#if f is the file
for line in f:
l.append({line.split(" ")[0]: line.split(" ")[1:]})
#It will append all the dicts into the list l
Hope it helps!!