I have a file which contains data in the following format: please note this is an example of what it looks like, the actual file contains more than 2 rows
1 30 5
2 64 4
I read in the file, convert the text to integers, and store them into a list. This is done with the following code:
file = open("dataFile.txt", "r")
items = []
for line in file:
line = map(int,line.split()) #convert the text data to integers
items.append(line) #add text data to list
The current format for the list looks like:
[[1, 30, 5], [2, 64, 4]]
I need to turn my list of lists into a dictionary. How would one go about doing this?
Dictionary key should be the first element
I'm going to play guess-what-you-want, and assume the first numbers in each row are in fact some kind of sequential identifier, and you want
1 30 5
2 64 4
to become
1 : [30, 5]
2 : [64, 4]
so...
with open("dataFile.txt") as dataFile:
items = {}
for line in dataFile:
line = map(int, line.split()) #convert the text data to integers
key, value = line[0], line[1:]
items[key] = value
(and I've changed the name of file
because file()
is already a builtin function in Python, and reusing that name for something else is bad form).
Or you could use a dictionary comprehension instead, starting with your items list:
itemDict = {item[0]: item[1:] for item in items}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With