Search code examples
pythondictionarytypeerror

TypeError: string indices must be integers when extracting values from dictionary


I get TypeError: string indices must be integers when using the following code to return the values from a key in a dictionary:

ids_batch = [x['acn_num_ACN'] for x in meta_batch]
ids_batch

The dictionary (meta_batch) is structured as:

{'acn_num_ACN': ['1107876', '1784088', '1216003'], 'Time_Date': ['201308', '202012', '201411']}

I appreciate I can get the values of the given key by using meta_batch['acn_num_ACN'] however, I feel the initial code should work... Grateful of any insight!


Solution

  • The items in your list comprehension are strings, not dictionaries. You can index (with integer indexes) into strings, but strings have no keys. That's what the error message is telling you.

    meta_batch = {'acn_num_ACN': ['1107876', '1784088', '1216003'], 'Time_Date': ['201308', '202012', '201411']}
    
    meta_batch_keys = [x for x in meta_batch]
    print(meta_batch_keys)
    # ['acn_num_ACN', 'Time_Date']
    
    meta_batch_keys_types = [type(x) for x in meta_batch]
    print(meta_batch_keys_types)
    # [<class 'str'>, <class 'str'>]
    
    meta_batch_keys_substrs = [x[0:2] for x in meta_batch]
    print(meta_batch_keys_substrs)
    # ['ac', 'Ti']
    

    You need this, probably:

    meta_batch = {'acn_num_ACN': ['1107876', '1784088', '1216003'], 'Time_Date': ['201308', '202012', '201411']}
    ids_batch = meta_batch['acn_num_ACN']
    print(ids_batch)
    # ['1107876', '1784088', '1216003']
    
    # or convert strings to integers:
    ids_batch = [int(i) for i in meta_batch['acn_num_ACN']]
    print(ids_batch)
    # [1107876, 1784088, 1216003]