For loop through list of strings

Question:

I am trying to save certain information out of xarray in a loop. I keep getting an error msg.
Here is an example:

import numpy as np
import pandas as pd
import xarray as xr

samples = {}

samples['first'] = [1,2]
samples['second'] = [3,4]

samples

categories = list(samples.keys())

categories

dta = []

for i in range(len(categories)):
    dta[categories[i]] = samples[categories[i]]

dta

I get an error saying "TypeError: list indices must be integers or slices, not str"

Asked By: Stata_user

||

Answers:

You should do this to add data:

for i in range(len(categories)):
    dta.append(samples[categories[i]])

Instead of:

for i in range(len(categories)):
    dta[categories[i]] = samples[categories[i]]

dta is a list

You can also do a list comprehension if you want:

dta = [samples[categories[i]] for i in range(len(categories))]
#[[1, 2], [3, 4]]

Edit:

dta = {}

for i in range(len(categories)):
    dta[categories[i]] = samples[categories[i]]

print(dta)

{'first': [1, 2], 'second': [3, 4]}
Answered By: God Is One

You can simplify the code to this:

samples = {
    "first": [1, 2],
    "second": [3, 4],
}

dta = list(samples.values())
print(dta)  # Output: [[1, 2], [3, 4]]

It basically takes list of all the values in the dictionary samples.

Answered By: Ashyam

Variable samples is of type dict

samples = {}

samples['first'] = [1,2]
samples['second'] = [3,4]

It has textual keys first, second of type str.

To add those values to variable dta of type list

Your code has issues:

dta = []

for i in range(len(categories)):
    dta[categories[i]] = samples[categories[i]]

Will fail because categories[i] references the list-element correctly by integer index i but, the value of element is a string which can’t be used to index the list dta.

Correct indexing would be dta[i] if the list has an element at position i. But your list is initially empty, see dta = []. So you have to use append().

Fix

Instead of a for-i loop using range(len(categories)) you can also use a for-each loop:

dta = []
for value in samples.values():
    dta.append( value )

Another simpler approach would be direct conversion during definition:
dta = list(samples.values())

Compare both data-structures afterwards in the Python shell:

>>> samples
{'first': [1, 2], 'second': [3, 4]}
>>> dta
[[1, 2], [3, 4]]
Answered By: hc_dev
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.