Home > Net >  I want to get the randomly picked key value from the dictionaries list but I got a type error.(note
I want to get the randomly picked key value from the dictionaries list but I got a type error.(note

Time:06-16

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

https://www.learndatasci.com/solutions/python-typeerror-list-indices-must-be-integers-or-slices-not-str/#:~:text=This type error occurs when,using the int() function.

if u want to want the full file for the code ask me ok. it is a work in progress

CodePudding user response:

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)

CodePudding user response:

Your variable "data" is a list with two dictionaries in it. With "data_name = data["name"]" you try to access this list but "name" is not an integer, so you get the TypeError. Your list only has two entries, so you can access it with data[0]["name"] or data[1]["name"].

Edit: Iterating over the dicts in your list as Mazimia stated, seems like a good idea.

  • Related