I am trying to figure out to store content of the file into multiple values in the specific key.
Desired output:
{'city1':[Island-1,Island-3],'city2':[Island-2,Island-4]}
data.txt
city1-south:"London"
city1-south:"Paris"
city1-north:"Amsterdam"
city1-north:"Island-1"
city2-south:"Island-2"
city1-east:"Island-3"
city2-west:"Island-4"
def readFile(data_file):
data = open(data_file,"r")
d = {}
for line in data:
if 'Island' in line:
city,loc = line.rstrip("\n").split(":",1)
d[city] = loc
print (d)
data.close()
data_file = "data.txt"
readFile(data_file)
Current output:
{'city2-south': '"Island-2"', 'city2-west': '"Island-4"', 'city1-east': '"Island-3"', 'city1-north': '"Island-1"'}
I can not run your code now because config_file is not defined. I have made some modifications so that your code can run.
with open("data.txt") as data:
d = {'city1': [], 'city2': []}
for line in data:
if 'Island' in line:
city,loc = line.rstrip("\n").split(":",1)
for key in d.keys():
if key in city:
d[key].append(loc[1:-1])
print(d)
Results:
{'city1': ['Island-1', 'Island-3'], 'city2': ['Island-2', 'Island-4']}
For now Island-1 etc. can noly be output as string in the dictionary since otherwise python would treat them as variables.
Related
I have a txt file which contains data in the format:-
name1: #(for student 1)
name2, 1
name3, 0
name4, 1
…
name2: #(for student 2)
name1, 0
name3, 0
name4, 0
…
and so on for different students.
and the dictionary created should be in the format:-
{"name1": {"name2" : 1, "name3" : 0,......},
"name2": {"name1" : 0, "name3" : 0, ......},
.....}
pls Solve the question without importing any module, simply by file i/o and nested dictionary*
My knowledge of nested dictionaries isn't great, so the furthest I've been able to get is reading the lines into a list, which is not the desired output
d = {}
with open (filename) as f:
content = f.readlines()
for line in content:
line = line.strip('\r').strip('\n').split(',')
d[line[0]] = line
You need to check if it's a name: line or a name, number line.
When it's name: start a new nested dictionary with that name, otherwise add to the current nested dictionary.
d = {}
with open(filename) as f:
for line in f:
line = line.strip()
if line.endswith(':'):
name = line[:-1]
d['name'] = {}
elif line:
innername, value = line.split(',')
d['name'][innername] = int(value)
I'm assuming the comments like #(for student 1) are not part of the file, just description here.
I have one nested list, and one list for "numbers"
test_keys = [["tobbe", "kalle"],["karl", "Clara"],["tobbe"],["tank"]]
test_values = ['123', '234','345','456']
res = {}
for key in test_keys:
for value in test_values:
res[value] = key
test_values.remove(value)
break
with open("myfile.txt", 'w') as f:
for key, value in res.items():
f.write('%s;%s;\n' % (key, value))
This provides the file
123;['tobbe', 'kalle'];
234;['karl', 'Clara'];
345;['finis'];
456;['tank'];
now I want to load the data back into the a dictionary without the ";" and later on back into the corresponding lists.
Try this:
res = {}
with open("myfile.txt") as file:
for line in file:
chunks = line.split(';')
names = chunks[1][1:-1].split(', ')
res[chunks[0]] = [name[1:-1] for name in names]
print(res)
test_keys = []
test_values = []
for key in res:
test_keys.append(key)
test_values.append(res[key])
print(test_keys)
print(test_values)
here is my txt file that has contained all of the lines. What I want to do is create a dictionary, and access a key, and get a list of values
Finance:JPMC
Software:Microsoft
Conglomerate:L&T
Conglomerate:Amazon
Software:Palantir
Defense:BAE
Defense:Lockheed
Software:TCS
Retail:TjMax
Retail:Target
Oil:Exxon
Oil:Chevron
Oil:BP
Oil:Gulf
Finance:Square
FMCG:PnG
FMCG:JohnsonNJohnson
FMCG:Nestle
Retail:Sears
Retail:FiveBelow
Defense:Boeing
Finance:Citadel
Finance:BridgeWater
Conglomerate:GE
Conglomerate:HoneyWell
Oil:ONGC
FMCG:Unilever
Semiconductor:Intel
Semiconductor:Nvidia
Semiconductor:Qualcomm
Semiconductor:Microchip
Conglomerate:Samsung
Conglomerate:LG
Finance:BoA
Finance:Discover
Software:TCS
Defense:Raytheon
Semiconductor:Microsemi
Defense:BAE
Software:Meta
Oil:SinoPec
Defense:Saab
Defense:Dassault
Defense:Airbus
Software:Adobe
Semiconductor:TSMC
FMCG:CocoCola
FMCG:Pesico
Retail:Kohls
Here is my attempted code
f = open("companyList.txt", "r")
sector, company = [], []
for line in f:
first, second = line.split(":")
sector.append(first)
company.append(second)
dictionary = {}
for key in sector:
for element in company:
dictionary[sector].append(element)
print(dictionary)
Since there are multiple duplicate keys, I wanted to append a list to that particular key as python doesn't allow duplicate keys.
If i understand your question right you can do this:
from collections import defaultdict
dictionary = defaultdict(list)
for line in f:
first, second = line.split(":")
dictionary[first].append(second)
I think this is what you want:
pairs = {}
with open("tst.txt", "r") as f:
while True:
line = f.readline().strip()
if not line:
break
sector, value = line.split(":", 1)
if sector not in pairs:
pairs[sector] = []
pairs[sector].append(value)
f.close()
print(pairs)
you should do:
f = open("companyList.txt", "r")
sector, company = [], []
for line in f:
first, second = line.split(":")
sector.append(first)
company.append(second)
dictionary = {}
for sectory,companyy in zip(sector,company):
dictionary[sectory] = companyy
for key in sector:
dictionary[sector] = key
So far I have this code which is creating a dictionary from an input file:
def read_file(filename):
with open("menu1.csv") as file:
file.readline()
for line in file:
line_strip = [line.rstrip('\n')]
lines= [line.split(',')]
result = {key: (float(fl), int(intg),
text.strip()) for key,
fl, intg,text in lines}
print(result)
read_file("menu1.csv")
I have to keep that code in that def format. However, this outputs 27 different dictionaries. How do I make it so it is all in ONE dictionary?
ALso:
I want to alphabetize the keys and put them into a list. I tried something like this but it won't work:
def alphabetical_menu(dict):
names = []
for name in d:
names.append(name)
names.sort()
print(names)
What am I doing wrong? or do you have a way to do it?
Is this what you wanted?
def read_file(filename):
result = {}
with open(filename) as file:
file.readline()
for line in file:
line_strip = line.rstrip()
line_split= line.split(',')
key, fl, intg, text = tuple(line_split)
result[key] = (float(fl), int(intg), text.strip())
return result
def alphabetical_menu(d):
return sorted(d.keys())
menu_dict = read_file("menu1.csv")
menu_sorted_keys = alphabetical_menu(menu_dict)
# To check the result
print(menu_dict)
print(menu_sorted_keys)
This is the data I have in my data.txt file
{"setup": "test", "punchline": "ok", "numOfRatings": 0, "sumOfRatings": 0},
{"setup": "test2", "punchline": "ok2", "numOfRatings": 0, "sumOfRatings": 0}
How would I be able to get only data from every setup in the
dictionaries using a loop?
Thanks
I'm not sure how you're getting the dictionaries into your text file in the first place, but if it's possible to drop the trailing commas, i.e.
{"setup": "test", "punchline": "ok", "numOfRatings": 0, "sumOfRatings": 0}
{"setup": "test2", "punchline": "ok2", "numOfRatings": 0, "sumOfRatings": 0}
Something like this may work for you:
def dicts_from_file(file):
dicts_from_file = []
with open(file,'r') as inf:
for line in inf:
dicts_from_file.append(eval(line))
return dicts_from_file
def get_setups(dicts):
setups = []
for dict in dicts:
for key in dict:
if key == "setup":
setups.append(dict[key])
return setups
print get_setups(dicts_from_file("data.txt"))
f = open('data')
for line in f:
d = ast.literal_eval(line)[0]
print d['setup']
for this code you need to put ',' after every line because ast.literal_eval(line) convert line into a tuple.
and if you do not have ',' after every dict then use this
f = open('data')
for line in f:
d = ast.literal_eval(line)
print d['setup']
You can try this if the line in your file is standard dict string.
def get_setup_from_file(file_name):
result = []
f = open(file_name, "r")
for line in f.xreadlines():
# or line_dict = json.loads(line)
line_dict = eval(line) # if line end witch ',', try eval(line[0:-1])
result.append(line_dict["setup"])
return result
Wish this can help you.
if it is standard dict string, try this:
with open(file,'r') as file_input:
for line in file_input:
print eval(line).get("setup")