Search code examples
pythonpandasdictionarykey

How can I print a value from dictionary on the below code?


I'm working on a code that takes data from different excel workbooks and someone recommended me to put those data into dictionary. Here is the code:

d={}
for file in range(len(filenames)):
    d[f'{file}'] = pd.read_excel(filenames[file], nrows = 32, usecols="A:D").fillna("")

The problem is I don't know how to print a specific value from my dictionary now.

print(d.keys()) shows me an answer: dict_keys(['0', '1'])

The code below works fine:

for key in d:
  print (d[key])

But when I write: print(d[1]) I get an error "KeyError: 1"


Solution

  • Dictionaries dont use indices to refence items in the dictionary likes lists and tuples. In for key in d: print (d[key]) if you print out key, you will see what the keys are. then you can reference them individually by print(d["key_name"])

    To display them as print(d[1]) change the keys to integers rather than strings d[f'{file}'] to d[file]