Skip to main content
 首页 » 编程设计

python将字典添加到现有字典之AttributeError : 'dict' object has no attribute 'append'

2025年05月04日23pengyingh

我正在尝试附加一个现有的 JSON 文件。当我覆盖整个 JSON 文件时,一切正常。我一直无法解决的问题在附录中。在这一点上我完全不知所措。

{ 
"hashlist": { 
    "QmVZATT8jWo6ncQM3kwBrGXBjuKfifvrE": { 
        "description": "Test Video", 
        "url": "" 
    }, 
    "QmVqpEomPZU8cpNezxZHG2oc3xQi61P2n": { 
        "description": "Cat Photo", 
        "url": "" 
    }, 
    "QmYdWb4CdFqWGYnPA7V12bX7hf2zxv64AG": { 
        "description": "test.co", 
        "url": "" 
    } 
} 
}% 

这是我使用的代码,其中 data['hashlist'].append(entry) 收到 AttributeError: 'dict' object has no attribute 'append'

#!/usr/bin/python 
 
import json 
import os 
 
 
data = [] 
if os.stat("hash.json").st_size != 0 : 
    file = open('hash.json', 'r') 
    data = json.load(file) 
   # print(data) 
 
choice = raw_input("What do you want to do? \n a)Add a new IPFS hash\n s)Seach stored hashes\n  >>") 
 
 
if choice == 'a': 
    # Add a new hash. 
    description = raw_input('Enter hash description: ') 
    new_hash_val = raw_input('Enter IPFS hash: ') 
    new_url_val = raw_input('Enter URL: ') 
    entry = {new_hash_val: {'description': description, 'url': new_url_val}} 
 
    # search existing hash listings here 
    if new_hash_val not in data['hashlist']: 
    # append JSON file with new entry 
       # print entry 
       # data['hashlist'] = dict(entry) #overwrites whole JSON file 
        data['hashlist'].append(entry) 
 
        file = open('hash.json', 'w') 
        json.dump(data, file, sort_keys = True, indent = 4, ensure_ascii = False) 
        file.close() 
        print('IPFS Hash Added.') 
        pass 
    else: 
        print('Hash exist!') 

请您参考如下方法:

通常 python 错误是不言自明的,这是一个完美的例子。 Python 中的字典没有 append 方法。有两种添加到字典的方法,要么通过命名新的键值对,要么将带有键值对的可迭代对象传递给 dictionary.update()。在您的代码中,您可以:

data['hashlist'][new_hash_val] = {'description': description, 'url': new_url_val} 

或:

data['hashlist'].update({new_hash_val: {'description': description, 'url': new_url_val}}) 

第一个可能更适合您要执行的操作,因为第二个更适合您尝试添加大量键值对。

您可以在 Python 中阅读更多关于字典的信息 here.