I have a text file that contains the following data:
C1,0,0,0,0,0,10
C2,5,5,0,5,5,10
C3,10,10,0,10,10,10
I am bringing this data into my Python script with the ultimate goal of having it in the following format:
columnCoordDict = {'C1': [0,0,0,0,0,10], 'C2': [5,5,0,5,5,10], 'C3': [10,10,0,10,10,10]}
My method so far has been to bring the data into my script and then split it into two lists:
List 1 - a list containing the keys ('C1','C2', 'C3').
List 2 - a list containing the values (which represent x, y, z coords).
# Reading text file with frame data
frameData = open("frameData.txt","r")
data = frameData.read()
data = data.replace("\n", ",")
dataList = data.split(',')
# Creating list containing keys alone by slicing
dataListKeys = dataList[::7]
# Creating list containing values by list comprehension removing Keys from main list
dataListValues = [x for x in dataList if x not in dataListKeys]
dictData = {}
However, I am unsure now how to create the dict in the format I presented above. I tried a zip method where it produced:
{'C1': 0, 'C2': 0, 'C3': 0}
But I need multiple values to be assigned to each key. Does anyone have any recommendations?
You can do something like this:
frameData = open("frameData.txt","r")
dictData = {i.split(",")[0]: list(map(int, i.split(",")[1:])) for i in frameData.readlines()}
frameData.close()
I have managed to get the wanted result with this:
frameData = open("frameData.txt","r")
data = frameData.read().splitlines()
frameData.close()
columnCoordDict = {}
for line in data:
items = line.split(',')
columnCoordDict[items[0]] = list(map(lambda x: int(x), items[1:]))
print(columnCoordDict)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.