Home > Mobile >  Python string indices must be integers from API dict
Python string indices must be integers from API dict

Time:03-14

I'm reading a Dictionary from an API and I'd like to be able to read the key and value, normally I can do it like this: fill['key'], or fill['created_at'] but none work.

for fill in last_fill:
    key = fill
    # key = str(fill)
    print(f"key: {key}")
    # value = fill["'"  key   "'"] # string indices must be integers
    # value = fill["'",key,"'"]


for fill in last_fill:
    print(fill)

# OUTPUTS all the KEYS
# created_at
# product_id
# order_id
# user_id
# ... 

And this:

for key in last_fill:
    print(f"key: {key}") # OUTPUTS: fill: created_at
    fill = last_fill[key]
    print(fill["created_at"]) # and here the ERROR: string indices must be integers

CodePudding user response:

Doing a for .. in ... loop on a dict returns the keys of the dict. So your fill variable represents each key.

for key in last_fill:
    fill = last_fill[key]
    print(fill)

In your case you don't seem to actually need the key so you could simply do

for fill in last_fill.values():
    print(fill)

If you need keys and values

for item in last_fill.items():
    (key, value) = item
    print(key, value)
  • Related