A problem with dictionary (TypeError: string indices must be integers)

So, I am a new user of this site and I have a problem with dictionary function.

den = {
    'first_name': 'den',
    'last_name': 'elc',
    'age': '16',
    'city': 'slovakia',
}
for user, user_info in den.items():
    nameo = user_info['first_name']
    namei = user_info['last_name']
    age = user_info['age']
    city = user_info['city']
    print(f"tFirst name:{nameo}")
    print(f"tLast_name:{namei}")
    print(f"tAge:{age}")
    print(f"tCity:{city}")

Python prints this TypeError:

    Traceback (most recent call last):
  File "D:/PyCharm Community/pycharm/venv/Test.py", line 15, in <module>
    nameo = user_info['first_name']
TypeError: string indices must be integers

Any assumptions?

Answer

In this case you don’t need a for loop if you have an array of dictionaries then you need to consider using for loop. Here you can simply do like below.

den = {
    'first_name': 'den',
    'last_name': 'elc',
    'age': '16',
    'city': 'slovakia',
}
print(f"tFirst name:{den['first_name']}")
print(f"tLast_name:{den['last_name']}")
print(f"tAge:{den['age']}")
print(f"tCity:{den['city']}")