0
itemsInExistence = [{'name': 'Tester', 'stats': 1, 'rank': 1, 'amount': 1}, {'name': 'Mk II Death', 'stats': 10, 'rank': 5, 'amount': 3}]
def save_list2():
  f = open('all_items.txt', 'w')
  ii = 0
  for item in itemsInExistence:
    print(f.write(itemsInExistence[ii][0], ''))
    f.write(itemsInExistence[ii][1] + ' ')
    f.write(itemsInExistence[ii][2] + ' ') 
    f.write(itemsInExistence[ii][3] + '\n')
    ii += 1

Where it says f.write(itemsInExistence[ii][0], '') it is giving me the error

KeyError: 0

Why is this and what does it mean? Is there any way to fix this?

PythonNerd
  • 293
  • 1
  • 11

1 Answers1

3

As @ggorlen said, use names as keys.

itemsInExistence = [{'name': 'Tester', 'stats': 1, 'rank': 1, 'amount': 1},
                    {'name': 'Mk II Death', 'stats': 10, 'rank': 5, 'amount': 3}]

def save_list2():
    with open('all_items.txt', 'w') as f:
        for item in itemsInExistence:
            f.write('{name} {stats} {rank} {amount}\n'.format(**item))

You need Python 3 for this example.

EDIT: I've changed print(..., file=f) to f.write(...), now it works in py2 and py3.

EDIT2: Some explanation.

with statement close file automatically.

Lists list or [] use positive integer indexes (0, 1 etc.)
Dictionaries dict or {} use keys (in your examples 'name', 'stats' etc.). See python docs.

for statement iterates by list items or by dict keys. You don't need ii, item is content of list item, which is dict.

for item in [1, 4, 'ala']:
   print(item)
# prints:
# 1
# 4
# 'ala'

for key in {'anwer': 42, 'sto': 100, 1: 'first'}:
    print(key)
# prints:
# 'answer'
# 'sto'
# 1

You can access dict values by my_dict[key] or iterate by values for value in my_dict.values or by keys and values: for key, value in my_dict.items().

I've used keyword arguments **item. In function call func(**{'a': 1, 'b': 2}) means func(a=1, b=2).

String format ''.format() (or format-string f'' since Python 3.6) allows put data directly to string with advanced syntax.

rysson
  • 180
  • 2
  • 10