我正在尝试一次将多个词典保存到列表中,同时保持其值不变,但是它不起作用

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

在说f.write(itemsInExistence [ii] [0],'')的地方,给了我错误

KeyError:0

这是为什么,这是什么意思?有什么办法可以解决这个问题?

fd1803 回答:我正在尝试一次将多个词典保存到列表中,同时保持其值不变,但是它不起作用

正如@ggorlen所说,将名称用作键。

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))

此示例需要Python 3。

编辑:我将print(...,file=f)更改为f.write(...),现在可以在py2和py3中使用了。

EDIT2:一些解释。

with语句关闭文件automatically

列表list[]使用正整数索引(01等)
字典dict{}使用键(在您的示例中,'name''stats'等)。参见python docs

for语句按列表项或dict键进行迭代。您不需要iiitem是列表项的内容,即字典。

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

您可以通过my_dict[key]访问字典值,也可以通过值for value in my_dict.values或通过键和值:for key,value in my_dict.items()进行迭代。

我使用了关键字参数**item。在函数调用中,func(**{'a': 1,'b': 2})的意思是func(a=1,b=2)

字符串格式''.format()(或者自Python 3.6起就是格式字符串f'')允许使用advanced syntax将数据直接放入字符串。

本文链接:https://www.f2er.com/3088751.html

大家都在问