Issue
def data_change(account):
data_name = data["name"]
data_desc = data["description"]
data_country = data["country"]
return f"{data_name}, is a {data_desc}, from {data_country}"
print(f"option A : {data_change(data_a)}")
The above code is data I want to process for the random data to display. the list dictionary below are the first 2 example data
data = [
{
'name': 'Instagram',
'follower_count': 346,
'description': 'Social media platform',
'country': 'United States'
},
{
'name': 'Cristiano Ronaldo',
'follower_count': 215,
'description': 'Footballer',
'country': 'Portugal'
}]
and the error display is TypeError: list indices must be integers or slices, not str
on the line: data_name = data["name"]
yes, I searched for numerous solutions but it didn't get my problem solved.
like from this link
if u want to want the full file for the code ask me ok. it is a work in progress
Solution
Data is a list and not a dictionary so you use zero based index to enumerate the items in the list. You could enumerate the items via a for loop like this:
def data_change(data):
ans = []
for account in data:
data_name = account["name"]
data_desc = account["description"]
data_country = account["country"]
ans.append(f"{data_name}, is a {data_desc}, from {data_country}")
return "\n".join(ans)
Answered By - Mazimia
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.