【问题标题】:I am Trying to Save Multiple Dictionaries to a List at a Time Whilst Keeping Their Values, But It Isn't Working [duplicate]我试图一次将多个字典保存到一个列表中,同时保留它们的值,但它不起作用[重复]
【发布时间】:2020-03-12 15:36:59
【问题描述】:
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], '') 它给了我错误

密钥错误:0

为什么会这样?这是什么意思?有没有办法解决这个问题?

【问题讨论】:

  • 使用item["name"]item["stats"] 等。您的字典中没有 0、1、2 等的键。
  • 在代码中,第一行已经产生了语法错误。最好将您的代码复制并粘贴到问题中。

标签: python dictionary save


【解决方案1】:

正如@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 语句通过列表项或字典键进行迭代。你不需要iiitem是list item的内容,就是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

您可以通过my_dict[key] 访问dict 值或通过值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将数据直接放入字符串。

【讨论】:

    猜你喜欢
    • 2021-05-02
    • 2022-01-25
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 2017-04-20
    相关资源
    最近更新 更多