Python nested dictionary error "string indices" [closed] - python

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 6 months ago.
Improve this question
This code is intended to display the inventory when inventory_check is called, then enable the player to select any item from the list by using the item_mod variable to display the name, type, and examine dialogue from the corresponding dictionary item.
# WEAPONS AND GEAR #
dicts={"bronze sword": {
"name": "Bronze Sword",
"type": "weapon",
"atk": "3",
"examine": "A shiny bronze sword.",
},
"turian garb": {
"name": "Turian Garb",
"type": "Armour",
"def": "1",
"examine": "Your combat uniform.",
},
"rusty buckler": {
"name": "Rusty Buckler",
"type": "Shield",
"def": '1',
"examine": "An old buckler, standard."
},
"test item": {
"name": "test",
"type": "weapon",
"atk": '1',
"examine": "Hope this works (:"
}
}
######################
def inventory_check():
os.system('clear')
print(inventory)
time.sleep(1)
mid_print("How would you like to interact with the inventory? Type the item and then what to do with it. \n")
mid_print("You can also type exit to leave the inventory. \n")
print(inventory)
item_mod = input(Green + "Which item to interact with? > \n" + reset)
if item_mod in inventory:
print (item_mod["name"])
print (item_mod["type"])
print (item_mod["examine"])
elif item_mod in ['leave', 'exit', 'e']:
location_check()
else:
mid_print("That is not an item in your inventory. remember to punctuate correctly. \n")
inventory_check()
However, it refuses to run the code, claiming "string indices must be integers". I haven't used integers, so am not sure where i have gone wrong. Thank you.

I guess you want to do
if item_mod in inventory:
print (inventory[item_mod]["name"])
print (inventory[item_mod]["type"])
print (inventory[item_mod]["examine"])
instead?

Related

Reading a JSON file in python, reading a value and assigning it to a variable [duplicate]

This question already has answers here:
How can I parse (read) and use JSON?
(5 answers)
Closed last month.
I have a json file which looks like
{
"0": {
"id": 1700388,
"title": "Disconnect: The Wedding Planner",
"year": 2023,
"imdb_id": "tt24640474",
"tmdb_id": 1063242,
"tmdb_type": "movie",
"type": "movie"
},
"1": {
"id": 1631017,
"title": "The Pale Blue Eye",
"year": 2022,
"imdb_id": "tt14138650",
"tmdb_id": 800815,
"tmdb_type": "movie",
"type": "movie"
},
"2": {
"id": 1597915,
"title": "The Man from Toronto",
"year": 2022,
"imdb_id": "tt11671006",
"tmdb_id": 667739,
"tmdb_type": "movie",
"type": "movie"
},
I am trying to read this and extract the "tmbd_id" to store as a variable. I then intend to inject this into a url for an api get request.
The next step is to add the response parameters to the json file. Then adding it all into a loop. There are 1000 entries.
I have been trying to use other answers but I suspect the nature of my json is causing the issue with the integer name causing issues. It has been giving me this error
for i in data['0']:
TypeError: list indices must be integers or slices, not str
You can use json.loads to read the file's content and then iterate to find those id's:
import json
tmdb_ids = []
with open('test.json', 'r') as json_fp:
imdb_info = json.load(json_fp)[0]
for dict_index, inner_dict in imdb_info.items():
tmdb_ids.append(inner_dict['tmdb_id'])
print(tmdb_ids)
Result:
[1063242, 800815, 667739]
You can make it more sophisticated if you need a specific tmdb_id from a specific "movie" by adding some if statements to the for loop, choosing movies you want.
Edit
I've noticed this is an array of dictionaries, thus we can iterate over each "movie chunk" and extract the tmdb_id from each one:
with open('test.json', 'r') as json_fp:
imdb_info = json.load(json_fp)
tmdb_ids = [movie_info['tmdb_id'] for movies_chunk in imdb_info for movie_index, movie_info in movies_chunk.items()]
for reading json:
import json
with open("file.json","r") as file:
text = json.load(file)
for tmbd_id:
for i in text:
print(text[i]["tmdb_id"])

I am trying to make a quiz app in python and want to display the question and options separately can someone help me?

questions = [
{
"num": 1,
"question": "What does XML stand for?",
"answer": "eXtensible Markup Language",
"options": [
"eXtensible Markup Language",
"eXecutable Multiple Language",
"eXTra Multi-Program Language",
"eXamine Multiple Language"
]
},
{
"num": 2,
"question": "Who invented C# Language?",
"answer": "Anders Hejlsberg",
"options": [
"Bjarne Stroustrup",
"Anders Hejlsberg",
"Charles Babbage",
"James Gosling"
]
},
]
i want to display the first question then user will enter the ans then it will go to next question
so i want help in displaying the question then it should display the next question
question_num = 1
while question_num < 2:
for question in questions:
print(questions[question_num - 1]["question"])
choice = questions[question_num - 1]["options"]
print(choice)
answer = input(" ")
question_num += 1
You use the while loop to continue to show the question and the for loop to iterate through the list with dictionaries and the variables are in the case, to cross-check the answers the user gives with the correct answer.
I hope this will help.
Well, lets see what you have.
questions: list[dict[str, int | str | list[str]]]
You should implement a function that gets an argument of that type, and that prints it as you want.
def ask(q: list[dict[str, int | str | list[str]]]) -> None:
...
For example it could be similar to the following:
def ask(q: list[dict[str, int | str | list[str]]]) -> None:
print(q["question"])
for i in q["options"]:
print(f"- {i}")

How do I compare user integer input to values in dictionary? (Python)

I'm working on a vending machine program and my code skips straight to the else statement instead of taking the user input and comparing it to the ID number in the list.
Here's the list and code:
`
itemstock = [
{
"idnum": 0,
"name": 'Water',
"price": 12,
},
{
"idnum": 1,
"name": 'Soda',
"price": 14,
},
{
"idnum": 2,
"name": 'Juice',
"price": 13,
},
]
choice = int(input("Now, choose an item ID from the Menu and enter the ID: "))
for i in itemstock:
if choice in ["idnum"]:
print("You have chosen item", choice)
else:
print("This is not a valid ID.")
break
`
I had hoped for if I had input the number 2, it would display what the user chose along with some text but it skips straight to the else statement. I've tried looking online but I may be doing something wrong here.
if choice in ["idnum"]
That is just a list containing the text "idnum". You want i["idnum"] instead:
for i in itemstock:
if i["idnum"] == choice:
print("You have chosen item", choice)
break
else:
print("This is not a valid ID.")
I also moved the else block out one level, so it is paired with the for loop, not the if statement. When a for loop iterates all the way to the end, the else block is executed (if it has one).

How to return data in specific format from Python Flask API?

I am writing a get API using python flask.
This API is for a FAQ webpage in which there are multiple question and answers which are divided section wise.
Webpage Example: How Webpage section looks for FAQ
**Section 1**
Question : Question 1 for section1?
Answer : Answer 1 for section 1.
Question : Question 2 for section1?
Answer : Answer 2 for section1.
**Section 2**
Question : Question 1 for section2?
Answer : Answer 1 for section 1.
Question : Question 2 for section2?
Answer : Answer 2 for section1.
I have written this python API code
#app.route('/getProductFaqs')
def productfaqs():
try:
conn = mysql.connect()
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute("SELECT id, product_name, product_question, product_answer FROM questionFAQ")
rows = cursor.fetchall()
resp = jsonify(rows)
resp.status_code = 200
return resp
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
which returns data in this format
[
{
"id": 1,
"product_answer": "answer product 1",
"product_name": "product 1",
"product_question": "What is product 1?"
},
{
"id": 2,
"product_answer": "answer product 2",
"product_name": "product 2",
"product_question": "What is product 2?"
},
{
"id": 3,
"product_answer": "answer product 3",
"product_name": "product 3",
"product_question": "What is product 3?"
},
{
"id": 4,
"product_answer": "answer product 4",
"product_name": "product 4",
"product_question": "What is product 4?"
}
]
However my requirement for API response is in this format
[
{
productid: 1[
{
Question: question1?
Answer: answer1.
},
{
Question: question2?
Answer: Answer2.
}
]
},
{
productid: 2[
{
Question: question1?
Answer: answer1.
},
{
Question: question2?
Answer: Answer2.
}
]
}
]
Can please someone help me out with this formatting of response.
Thankyou in Advance.
my friend. I have some tips for you.
First of all, you should not use a database connection like this.
This way, you can not easily use it in other parts of your program.
Second, It's usually better to use an ORM like Sqlalchemy integrated with Flask. It will help you satisfy also the first problem.
And for your question, you should parse the result of your query, tailor it to fulfill your requirements, and store it in a dictionary so that you can then return it as a JSON object.

How to do a length check using nested dictionary

I'm trying to make a length check on my dictionary as a form of simple validation. For example I'm trying to put a limit of number of players that can join a specific team which is a nested dictionary. Here's what I've done so far
teamS = {
"Team 1": {"Team Ahab":["Venom,Paz,Chico,Kaz,Miguel"],"Score":[],"Event":[]},
"Team 2": {"Team Ishmael":[],"Score":[],"Event":[]},
"Team 3": {"Team Miller":[],"Score":[],"Event":[]},
"Team 4": {"Team Raiden":[],"Score":[],"Event":[]}}
if len(teamS["Team 1"]["Team Ahab"]) > 5:
teamS["Team 1"]["Team Ahab"].pop(5)
print("This team is full so please join another one instead")
My ideal output would be like this
teamchoice = input("What team do you want to join) ("Team Ahab")
print("This team is full so please join another one)
This is poor design. You have two keys that make it harder for you to work. If you want to key by team name, that's fine, but don't make a redundant team ID. Just use a dictionary where the team is the key and the roster is a list of names, with built-in len.
teams = {
"Ahab": {
"roster": ["Venom", "Paz", "Chico", "Kaz", "Miguel"],
"Score": [],
"Event": []
},
"Ishmael" : {
"roster:[],
"Score": [],
"Event": []
},
...
}
Simply look up the given team; let's just call that pref_team.
if len(teamS[pref_team][roster]) >= 5:
# reject membership
That should be enough to get you moving.
Based on your code, to get the len of the team, you should do something like this:
print(len(str(teamS["Team 1"]["Team Ahab"]).split(",")))
You need to get the Dictionary inside the Team number, and then, the list of members is just an string separated by commas

Categories