Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 蟒蛇3。向现有键添加几个值_Python_Dictionary - Fatal编程技术网

Python 蟒蛇3。向现有键添加几个值

Python 蟒蛇3。向现有键添加几个值,python,dictionary,Python,Dictionary,我知道有很多关于这个主题的信息,但我真的被这个问题困住了 我从文件中加载了一本词典: datastore = json.load(f) print(datastore) {"a": "999", "b": "345"} 现在,我需要向现有键添加更多值 但是我收到了一个错误: AttributeError:“str”对象没有属性“append” 以下是我迄今为止所尝试的: if key in datastore: temp = [] [temp.extend([k, v]

我知道有很多关于这个主题的信息,但我真的被这个问题困住了

我从文件中加载了一本词典:

datastore = json.load(f)    
print(datastore)
{"a": "999", "b": "345"}
现在,我需要向现有键添加更多值

但是我收到了一个错误:

AttributeError:“str”对象没有属性“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)
以及:

结果是一样的:

“str”对象没有属性“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))

这无法工作,原因请参见备注:

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) 
(免责声明:代码未执行,可能包含拼写错误,请告诉我,我会修复)

内容如下:

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

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

如果键在字典中是而不是,它将在
数据存储中直接创建条目作为列表,使用刚刚解析的值作为列表中的默认值


然后全部存储回并替换当前文件

在向现有密钥添加值后,您能展示您期望数据存储的内容吗?很好,请阅读:这是帮助,非常感谢,但我真的不明白它是如何工作的=\Patrick,谢谢,这非常有帮助。我理解图片本身,但我忽略了这里发生的魔力:
val=datastore[key]#这里我将现有值取为val变量-ok如果type(val)==str:#执行检查-ok datastore[key]=[val]#这里有魔力!数据存储[key].append(value)
-#现在执行append时没有错误!又变魔术了!加载数据存储时,保存为字符串的前一个值将在数据存储中恢复为字符串。我检查它是否是字符串。如果是,我将其另存为列表。因此,值现在不再是字符串,而是包含字符串的列表。列表有
.append()
方法,可以将更多内容放入列表中。这就是它起作用的原因。。这与使用
sillyExample=[1,2,3]
a=1
+
b=1
+
c=1
+
sillyAgain=[a,b,c]
时相同-将变量的值存储在列表中。您将该键下存储的值的类型从“字符串”更改为“字符串列表”。没有魔法,很好。请随意标记为答案。如何:……对不起。完成。
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)