-1

I am simply trying to build a dictionary with keys from a list of strings and values that area list of numbers.

filepath = path
df = pd.read_excel(filepath, sheet_name=sheet)


columns = df.columns
fields = columns.to_list()
values = [1,2,3]
dict = {}

def build_dict(fields,values):
    for i in fields:
        dict[i] = fields[i]
    print(dict)

build_dict(fields,values)

I consistently end up with... TypeError: list indices must be integers or slices, not str

mikesc1
  • 9
  • 4
  • `fields` is a list of strings, so `i` is a string; the error is saying you can't do `fields[i]` –  Feb 18 '22 at 21:06
  • `for i in fields` already gives you the elements of `fields` in `i`. You can't do `fields[i]` again (unless `fields` is a list of integers and you really wanted to do this, but it's a list of strings) – Pranav Hosangadi Feb 18 '22 at 21:47
  • Does this answer your question? [How do I convert two lists into a dictionary?](https://stackoverflow.com/questions/209840/how-do-i-convert-two-lists-into-a-dictionary) – Pranav Hosangadi Feb 18 '22 at 21:48
  • (1) You shouldn't name a variable `dict`: that's overriding the dict type. (2) What about `values` - you're doing nothing with it in the function? – Timus Feb 19 '22 at 14:37

1 Answers1

0

You can make a dictionary from two lists as follows:

filepath = path
df = pd.read_excel(filepath, sheet_name=sheet)


columns = df.columns
fields = columns.to_list()
values = [1,2,3]
dict = dict(zip(fields, values))
Tyarel
  • 1
  • Welcome to Stack Overflow! Since it's a pretty basic question, you should look to see if the same question has been asked already before adding an answer. – Pranav Hosangadi Feb 18 '22 at 21:49