Add keys and values from a text file to a dictionary - python

I have a text file test.txt with two lines on it:
1 "test one"
2 "test two"
I just want to add those 2 lines to test_dict:
test_dict = {}
with open("test.txt", "r") as f:
for line in f:
(key, val) = line.split()
test_dict[int(key)] = val
print(test_dict)
Error:
ValueError: too many values to unpack (expected 2)
Expected result:
test_dict = {1: "test one", 2: "test two"}

After you edited your question, this should work :
test_dict = {}
with open("testtt.txt", "r") as f:
for line in f:
(key, val) = line.split(maxsplit=1)
test_dict[int(key)] = val
print(test_dict)
Because we need the first item as a key, and "rest of them" as value, so I pass maxsplit=1 as an argument to split(). This only split the line only 1 time from the left.

Related

create a nested dictionary from the input given in a text file in python

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.

Read dictionary from file into original lists

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)

Getting values from a line in a .txt file with Python

I have the difficulty of getting specific values from a line from a .txt file with python. For example from this line:
Packages: Sent = 5, Received = 7, Lost = 0
i would like to get the integer values.
I already tried to use a dictionary in the following way by trying to assign keys and values with a dictionary.
data = {}
with open("file.txt", "rt", errors = "ignore") as file:
lines = file.readlines()
for line in lines:
if "Packages:" in line:
line.split(":")
key1, value1, key2, value2, key3, value3 = line.split(" = ")
data[key1, key2, key3] = value1, value2, value3
print(value1, value2, value3)
I am a beginner, so please excuse me if this problem is trivial.
Thank you!
data = {}
with open("file.txt", "rt", errors = "ignore") as file:
lines = file.readlines()
for line in lines:
if "Packages:" in line:
line_vals=line.replace('Packages:', '').replace('\n','').split(',')
for j in line_vals:
vals=j.split('=') # here you can get each key and value as pair
key=vals[0] #here is your key
value =vals[1] # here is your value
You have to assign the splitted line to th variable
data = {}
with open("file.txt", "rt", errors = "ignore") as file:
lines = file.readlines()
for line in lines:
if "Packages:" in line:
line = line.strip().split(":")
key1, value1, key2, value2, key3, value3 = line.split(" = ")
data[key1, key2, key3] = value1, value2, value3
print(value1, value2, value3)
You're on the correct track, just a few issues in implementation:
data = {}
with open("file.txt", "rt", errors = "ignore") as file:
for line in file:
if "Packages:" in line:
# Remove all spaces in line
line = line.replace(" ", "")
# Remove "Packages:"
line = line.split(":")[1]
# Separate out each <key, value> pair
kv_pairs = line.split(",")
# Fill the dictionary
for kv in kv_pairs:
key, value = kv.split('=')
data[key] = value
Say you have the line
line = 'Packages: Sent = 5, Received = 7, Lost = 0'
To clean up each "word" from line.split(" = "), you may do e.g.
words = [word.strip(' ,:') for word in line.split()]
Note that split() (without argument) splits on whitespace.
If you know that you want e.g. element 3 (the str '5'), do
val = words[3]
You can even convert this to a proper int by
val = int(words[3])
Of course this fails if the str does not actually represent an integer.
Side note
Note that line.split(":") on its own has no effect, as the str line is not mutated (str's are never mutated in Python). This just computes a list of results and then throws it away as you do not assign this result to a variable.
to chek if a var is int you can use this:
i = 12
print(isinstance(i, int)) #True
i = "12"
print(isinstance(i, int)) #False
and in your example you just need to do it:
lines = ["Packages: Sent = 5, Received = 7, Lost = 0"]
data = {}
linenumber = 1
for line in lines:
line = line.split(": ")[1]
col = line.split(",")
dic = {}
for item in col:
item = item.split(" = ")
dic.update({item[0]:item[1]})
data.update({"1":dic})
linenumber += 1
print(data)
and if you need to check only values that is interger you should do it:
lines = ["Packages: Sent = 5, Received = oi, Lost = 0"]
data = {}
error=[]
linenumber = 1
for line in lines:
line = line.split(": ")[1]
col = line.split(",")
dic = {}
for item in col:
item = item.split(" = ")
try:
if isinstance(int(item[1]), int):
dic.update({item[0]:item[1]})
except:
error.add("Cannot convert str to int in line " + linenumber )
# nothing to do
data.update({"1":dic})
linenumber += 1
print(data)

How to sort the keys in a dictionary alphabetically and put them in a list?

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)

How to get values of one key from multiple dictionaries in python?

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")

Categories

Resources