Python3。向现有密钥添加少量值

问题描述 投票:-1回答:1

我知道有很多关于这个问题的信息,但我真的很困惑这个问题。

我有一个从文件加载的字典:

datastore = json.load(f)    
print(datastore)
{"a": "999", "b": "345"}

现在,我需要为现有密钥添加更多值。

但相反,我收到一个错误:

AttributeError: 'str' object has no attribute 'append'

这是我到目前为止所尝试的:

if key in datastore:
    temp = []
    [temp.extend([k, v]) for k, v in datastore.items()]
    print(temp)
    print(type(temp))
    i = temp.index(key)
    print(i)
    temp[i].append(value)
    print(temp)

和:

if key in datastore:
    datastore.setdefault(key, [])
    datastore[key].append(value)

结果是一样的:

'str' object has no attribute 'append'

请帮忙!

完整代码如下:

import os
import json
import argparse
import sys

if len(sys.argv) > 3:

  parser = argparse.ArgumentParser()
  parser.add_argument("--key")
  parser.add_argument("--val")
  args = parser.parse_args()

  key = args.key
  value = args.val

  storage = {}
  storage[key] = value

  if os.path.exists('storage_file'):
    with open('storage_file', 'r') as f:
      datastore = json.load(f)
      if key in datastore:
        datastore.setdefault(key, [])
        datastore[key].append(value)
      else:
        datastore.update({key: value})
      with open('storage_file', 'w') as f:
        json.dump(datastore, f)
  else:
    with open('storage_file', 'w') as f:
      json.dump(storage, f)

else:
  parser = argparse.ArgumentParser()
  parser.add_argument("--key", action="store")
  args = parser.parse_args()

  key = args.key

  with open('storage_file', 'r') as f:
    datastore = json.load(f)
    print(datastore.get(key))
python dictionary
1个回答
0
投票

这不行,原因见评论:

if os.path.exists('storage_file'):
   with open('storage_file', 'r') as f:
     datastore = json.load(f)
     if key in datastore:
       datastore.setdefault(key, [])   # key already exists, you just checked it, so it  
       datastore[key].append(value)    # will not create [], tries append to existing data
     else:
       datastore.update({key: value})
     with open('storage_file', 'w') as f:
       json.dump(datastore, f) 

您可以尝试使用以下方法修复它:

if os.path.exists('storage_file'):
   with open('storage_file', 'r') as f:
     datastore = json.load(f)
     if key in datastore:
       val = datastore[key]
       if type(val) == str:               # check if it is a string / if you use other
         datastore[key] = [ val ]         # types you need to check if not them as well
       datastore[key].append(value) 
     else:
       datastore.setdefault(key, [ value ])    # create default [] of value

     with open('storage_file', 'w') as f:
        json.dump(datastore, f) 

(免责声明:代码未执行,可能包含错别字,请告诉我,我会修复)

阅读次数:

您检查从命令行解析的密钥是否已存储到加载为datastore的json文件中。如果您有一个包含某个键的字符串的文件,则loadign它将始终将其重新创建为字符串。

您的代码检查密钥是否已经在datastore中 - 如果是,则新代码将值读入val。然后它检查val是否为str类型 - 如果是这样,它将datastore中的值替换为包含keyval列表。然后它附加您从命令行解析的新参数。

如果密钥不在字典中,它会直接在datastore中创建条目作为列表,使用刚刚解析的值作为列表中的defaultvalue。

然后将所有内容存储回来并替换当前文件。

© www.soinside.com 2019 - 2024. All rights reserved.