This is the txt file content I have:
salesUnits:500
priceUnit:11
fixedCosts:2500
variableCostUnit:2
I need to create a dictionary in Python that will read the file and make the keys the salesUnits etc. and the values the numbers. The code I have so far will only print the variable cost per unit:
with open("myInputFile.txt") as f:
content = f.readlines()
myDict = {}
for line in content:
myDict=line.rstrip('\n').split(":")
print(myDict)
How can I fix the code so that all key and value pairs show up? Thank you!
You're overwriting myDict each time you call myDict=line.rstrip('\n').split(":"). The pattern to add to a dictionary is dictionary[key] = value.
myDict = {}
with open("myInputFile.txt") as f:
for line in f:
key_value = line.rstrip('\n').split(":")
if len(key_value) == 2:
myDict[key_value[0]]=key_value[1]
print(myDict)
outputs
{'fixedCosts': '2500', 'priceUnit': '11', 'variableCostUnit': '2', 'salesUnits': '500'}
Using a simple dict comprehension will handle this:
with open('testinput.txt', 'r') as infile:
dict = {
line.strip().split(':')[0]:
int(line.strip().split(':')[1])
if line.strip().split(':')[1].isdigit()
else
line.strip().split(':')[1]
for line in infile.readlines()}
print(dict)
Output:
{'salesUnits': 500, 'priceUnit': 11, 'fixedCosts': 2500, 'variableCostUnit': 2}
If you wish to bring the numbers in as simple strings, just use:
dict = {
line.strip().split(':')[0]:
line.strip().split(':')[1]
for line in infile.readlines()}
Note also that you can add handling for other data types or data formatting using additional variations of:
int(line.strip().split(':')[1])
if line.strip().split(':')[1].isdigit()
else
myDict = {}
with open('dict.txt', 'r') as file:
for line in file:
key, value = line.strip().split(':')
myDict[key] = value
print myDict
Output:
{'fixedCosts': '2500', 'priceUnit': '11', 'variableCostUnit': '2', 'salesUnits': '500'}
Related
I've tried several methods to read from this file and turn it to a dictionary but I'm having a lot of errors
I've tried the following method but it did not work I got not enough values unpack.
d = {}
with open("file.txt") as f:
for line in f:
(key, val) = line.split()
d[int(key)] = val
I want to read and convert it to this:
{123: ['Ahmed Rashed', 'a', '1000.0'], 456: ['Noof Khaled', 'c', '0.0'], 777: ['Ali Mahmood', 'a', '4500.0']}
Split on commas instead.
d = {}
with open("file.txt") as f:
for line in f:
parts = line.rstrip('\n').split(',')
d[int(parts[0])] = parts[1:]
Using csv.reader to read the file and split it into its fields:
import csv
with open("file.txt") as f:
d = {
int(num): data
for num, *data in csv.reader(f)
}
This question already has answers here:
A better way to create a dictionary out of two lists with duplicated values in one
(2 answers)
Closed 1 year ago.
I have a question making a dictionary with text file.
I have a text file like this:
0,1
0,2
0,3
1,2
1,3
1,4
2,3
2,4
2,5
What I am trying to do,
I would like to make {0: [1,2,3], 1:[2,3,4], 2:[3,4,5]} like this
lists = {}
test = open('Test.txt', mode='r', encoding = 'utf-8').read().split('\n')
for i in test:
if len(lists) == 0:
lists[i.split(',')[0]] = [i.split(',')[1]]
In here, whenever I call for fuction, the value number is changed..
I am trying to figure out how I gotta do,
But it seems little bit tricky to me
Can anyone give me some advice or direction for it?
I really appreciate it
Thank you!
result = {}
with open('test.txt') as f:
for line in f:
key, value = line.strip().split(',')
if key not in result:
result[key] = [value]
else:
result[key].append(value)
print(result)
Output:
{'0': ['1', '2', '3'], '1': ['2', '3', '4'], '2': ['3', '4', '5']}
You can also try the defaultdict collection which is more convinent.
Here is an approach with a defaultdict. map with the reference to the int function is used to convert the strings to integers.
from collections import defaultdict
result = defaultdict(list)
with open('Test.txt', mode='r', encoding='utf-8') as infile:
for line in infile:
key, value = map(int, line.split(','))
result[key].append(value)
print(result)
The result is
defaultdict(<class 'list'>, {0: [1, 2, 3], 1: [2, 3, 4], 2: [3, 4, 5]})
Besides the bonus of the default value it will behave like a normal dictionary.
The following code does what I want, but any other way more python-style of doing it?
Having file in the format:
key1:value1,key2:value2,...
key21:value21,key22:value22,...
.
EOF
and code:
file = open(fileName, 'r')
for lines in file:
line = lines.split(",")
my_dict = {}
for item in line:
key_value = item.split(":")
my_dict.update({key_value[0]:key_value[1]})
Thanks
A faster & more pythonic way would be to use csv module (comma separated by default) and split items in a double flattened generator comprehension fed to dict that accepts tuples with 2 elements:
import csv
with open("test.csv",newline="") as f: # replace ,newline="" by ,"rb" in python 2
cr = csv.reader(f)
d = dict(x.split(":") for row in cr for x in row)
print(d)
result:
{'key1': 'value1', 'key22': 'value22', 'key21': 'value21', 'key2': 'value2'}
non-csv version:
import csv
with open("test.csv") as f:
d = dict(x.split(":") for line in f for x in line.split(","))
Using split():
list.txt:
key1:value1,key2:value2,key3:value3
key21:value21,key22:value22
Hence:
with open("list.txt") as fileObj:
content = fileObj.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]
for line in content:
for elem in line.split(","):
print({elem .split(":")[0] : elem.split(":")[1]})
OUTPUT:
{'key1': 'value1'}
{'key2': 'value2'}
{'key3': 'value3'}
{'key21': 'value21'}
{'key22': 'value22'}
OR
If you want them stored in the dict:
for line in content:
for x in line.split(","):
dict_.update({x.split(":")[0] : x.split(":")[1]})
print(dict_['key1']) # value1
I have the following tab-delimited text file:
1 John 27 doctor Chicago
2 Nick 33 engineer Washington
I am trying to convert it into a python dictionary where the key is the NAME and the age, career and address are the values. I would like to exclude the rankings (1, 2).
Code:
myfile = open ("filename", "r")
d = { }
for line in myfile:
x = line.strip().split("\t")
key, values = int(x[0]), x[1:]
d.setdefault(key, []).extend(values)
print(d)
You can convert it to a dict indexed by name with values in tuples instead:
d = {}
with open('filename', 'r') as myfile:
for line in myfile:
_, name, *values = line.strip().split("\t")
d[name] = values
print(d)
With your sample input, this will output:
{'John': ('27', 'doctor', 'Chicago'), 'Nick': ('33', 'engineer', 'Washington')}
You don't explain what difficulties you face.
However, from that sample of tab-delimited text, and you want to have dict like:
{'John': ['27', 'doctor', 'Chicago'], 'Nick': ['33', 'engineer', 'Washington']}
If that's the output you want to reach, then I modified your code a bit.
myfile = open ("filename", "r")
d = { }
for line in myfile:
x = line.strip().split("\t")
key, values = x[1], x[2:]
d.setdefault(key, []).extend(values)
print(d)
I need to put all the words in the txt file into a dictionary:
For example, I have the f.txt like this:
a tom
a sam
b stern
c stern
a king
I expect to get:
{'a': 'tom', 'sam', 'king', 'b':'stern', 'c': 'stern'}
Here's my code
new_dict = {}
myFile = open('f.txt', 'r')
for line in myFile:
line2=line.split()
group=line2[0]
name=line2[1]
new_dict[group]= name
new_dict
There is an issue with this code. The output does not read this file well, I only get part of the keys and values, not all of them.
for example:
I got this:
{'a': 'tom', 'b':'stern'}
How to deal with this?
You cannot associate multiple values with one key like that. You should use tuples or lists.
With your current code you end up over-writing the last list item you added to the dictionary. Instead, try
for line in myFile:
line2 = line.split()
group = line2[0]
name = line2[1]
if group in new_dict:
new_dict[group].append(name)
else: # Create new list if it doesn't exist
new_dict[group] = [name]
print new_dict
That would give you an output of
{'a': ['tom', 'sam', 'king'], 'b':['stern'], 'c': ['stern']}