"+=" operator not working when modifying .json in variable (Python) [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm new to Python, and I'm trying to store data in a .json, and then access and modify it through Python. Currently I'm having an issue where I can't modify the data if I try to use a variable instead of directly modifying it. It works fine if it's not in a variable, or if I'm just reading the information, or if it's not in a function.
import json
with open('testprog.json', 'r+') as f:
data = json.load(f)
x = int(data['valueOne'])
def test():
x += 1
#VSC tells me this variable is not defined.
#If I swap the variable for “int(data[‘valueOne’])” it works.
f.seek(0)
json.dump(data, f, indent=4)
f.truncate()
test()
print("New first value is: "+str(data['valueOne']))
.json:
{
"valueOne": 10,
"valueTwo": 5,
"valueThree": 8
}

I assume that the value associated with the key valueOne is a string. Therefore you could do this:
data['valueOne'] = str(int(data['valueOne']) + 1)

Related

How to create function using list that corresponds content to content within the list? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 months ago.
Improve this question
The following string contains a list of positions and the corresponding persons. I have tried to create a function that, given a person, returns the list of positions the person has. But I get this error "AttributeError: 'function' object has no attribute 'split'". I am wondering if I could place a len function to make this code work (But I don't know where to place it, or do you have other solutions?
positions = '''\
== Positions ==
manager: Kari
treasurer: Ole
IT manager: Liv
parking officer: Kari
event manager: Liv
garden consultant: Kari
fire officer: Kari
'''
positions=positions.split("\n")
def match_job_to_person(person):
lines = match_job_to_person.split("\n")
for line in lines:
words = line.split(": ")
if(words[0] == person):
return words [1]
print (words)
match_job_to_person("Kari")
match_job_to_person("Ole")
match_job_to_person("Liv")
Switch:
lines = match_job_to_person.split("\n")
for
lines = positions.split("\n")
or
lines = positions
(since you did the newline split outside of your function already)
Your reference in the function to match_job_to_person is a reference to the function name, this isn't a string but a function, and as such, doesn't provide the split method.
There are other problems with your code, but this should move you past the initial error you're getting.

Key Error even though key IS in dictionary? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Dictionary:
section of dictionary
My Code:
code
Error says:
3
So how come the date key works fine but for freq it fails?
ps. my first time posting, so am very sorry for the sloppy structure of the post
This can only happen when one of your day is missing the freq parameter.
Try catching the day in which the error is happening. Then manually check that particular entry.
date_list = []
frequency_list = []
try:
for i in obj:
date = obj[i]["date"]
frequency = obj[i]["freq"]
date_list.append(date)
frequency_list.append(frequency)
except:
print(i)

How to get value from a JSON file using key? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am new to python. I am trying to get value from a JSON File.
Here is my JSON file stored in static/tokens.json
{
"872387":"ABC",
"821483":"XYZ",
"575652":"KLM"
}
I want to read the get the value of Key(821483). which is XYZ.
Here is what I am doing
I am reading Json file
token = json.load(open(os.path.join(app.root_path, "static", "tokens.json")))
print(token['821483'])
But it gives me this error:
print(token['821483']) TypeError: string indices must be integers
I have also tried this
with open(os.path.join(app.root_path, "static", "tokens.json")) as read_file:
data = json.load(read_file)[1]
print("Type of deserialized data: ", type(data))
print(data['821483'])
But Again I am getting the same error.
I have seen similar questions on Stackoverflow. And what I have understood so far is that
tokens = json.load(open(os.path.join(app.root_path, "static", "tokens.json"))) converts Json to a List. How can I solve this problem? I don't want to change the structure of JSON file.
How can I convert this JSON file into a dictionary not into a list so that I can access the values using a key?
When you use json.load() python automatically converts to dict, see here so you don't need to convert to dict again
import json
data = json.load(open("static/tokens.json"))
Now check what is in data and the type of data:
{'872387': 'ABC', '821483': 'XYZ', '575652': 'KLM'} <class 'dict'>
We sucessfully convert it to dict so now you can iterate:
for key, value in data.items():
if key == "821483":
print({key: value})
Out: {'821483': 'XYZ'}
If you don't want to iterate you can simply use dict_object.get(value)
print(data.get("821483"))
Out: XYZ

How to Avoid Duplicate Data [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
while True:
if bbs_number > lately_number():
sys.stdout = open('date.txt','a')
bbs_lists = range(highest_number() +1, bbs_number +1)
for item in bbs_lists:
url_number = "url" + str(item)
try:
result = requests.get(url_number)
bs_number = BeautifulSoup(result.content, "lxml")
float_box = bs_number.find("div", {"class": "float_box"})
parameter_script = float_box
print("bs_obj()")
except AttributeError as e:
print("error")
with open('lately_number.txt', 'w') as f_last:
f_last.write(str(bbs_number))
Using the while statement above does not cause an error, but duplicate data will be output to date.txt.
I want to modify in the early stages of setting the range value, rather than removing duplicates in the later stages of typing in date.txt.
One possibility is that the existing lately_number() will output a duplicate range to date.txt, because sometimes it is not possible to enter the value correctly in the writing process of lately_number.txt.
I would be grateful if you can help me with a better function expression to add or replace.
The simplest way would be to read the date.txt into a set. Then, you can check the set to see if the date is already in there, and if it isn't, write the date to the date.txt file.
E.G.
uniqueDates = set()
#read file contents into a set.
with open("date.txt", "r") as f:
for line in f:
uniqueDates.add(line.strip()) #strip off the line ending \n
#ensure what we're writing to the date file isn't a duplicate.
with open("date.txt", "a") as f:
if("bs_obj()" not in uniqueDates):
f.write("bs_obj")
You'll probably need to adjust the logic a bit to fit your needs, but, I believe this is what you're trying to accomplish?

How can I take a value from a document and add another value to it? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have a Python program I'm writing that I would like to have track statistics given inputs. I'd like it to have two documents set up, and be able to refer to each. In each, there would be a value, let's say it's x. The program would be able to generate a number, and I'd like to be able to update the number in a given document by adding the generated number. Right now, my code would be as follows:
f1 = open("player1records.txt", "a+")
f1.write(str(int(P1wins) + int(f1.read)))
This, however, raises the following:
TypeError: int() argument must be a string, a bytes-like object or a number,
not 'builtin_function_or_method'
How can I take that x and add another number to it, then update the document?
don't forget to add the () to the end of a function to call it:
f1.write(str(int(P1wins) + int(f1.read()))) # not f1.read
this sort of thing is difficult to do safely, one tends to end up with code that does:
from os import replace
def updateRecords(value, filename="player1records.txt"):
try:
with open(filename) as fd:
prev = int(fd.read())
except (FileNotFoundError, ValueError):
prev = 0
changed = prev + value
# write to a temp file in case of failure while doing this
tmpname = filename + '~'
with open(tmpname, 'w') as fd:
fd.write(str(changed))
# perform atomic rename so we don't end up with a half written file
replace(tmpname, filename)
all of this fiddling is why people tend to end up hiding this complexity behind a relational database. Python includes a relatively nice SQLite interface. if everything was set up, you'd be able to do:
with dbcon:
dbcon.execute(
"UPDATE player SET wins=wins + ? WHERE player_id = ?",
(P1wins, 1))
and have the SQLite library take care of platform specific fiddly bits…

Categories