I have following code and want now to add all items of "Produkt-Name" to a Dictionary
for col_number, element in enumerate(headings):
for row in ws.iter_rows():
if row[col_number].value is None:
continue
else:
if element == "Produkt-Name":
test = {"productname": row[col_number].value}
The Problem is, I only get the last item of it at the dictionary. I also tested the build in update function but got the last index too.
CodePudding user response:
Every time your conditions are met (the two if statements) you create a new dictionary called "test", the proper syntax to add elements to a dict is :
my_dict[new_key] = value
if new_key already exists, then you will overwrite the old value with the new one, without creating a new key/value pair. Hope this helps.
Also, as others already pointed out, please produce a minimal reproducible example, we at least need the structure of "headings" and what you would expect as an output.
CodePudding user response:
if you want to have all items under the key 'productname' you can use:
test.setdefault("productname", []).append(row[col_number].value)
but if you want to have your values under different keys you need to set different key names, instead of using the same for all (like the key 'productname' in your example)