Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to get the randomly picked key value from the dictionaries list but I got a type error.(note the list is long so putting a index is difficult)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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%20type%20error%20occurs%20when,using%20the%20int()%20function.

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading