python add dictionary to existing dictionary AttributeError:“dict”对象没有“append”属性

2024-04-24 22:21:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

这是我正在使用的代码,其中data['hashlist'].append(entry)receive AttributeError:'dict'object没有属性'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!')

Tags: jsonurlnewinputdatarawvalhash
1条回答
网友
1楼 · 发布于 2024-04-24 22:21:59

通常,python错误是非常不言而喻的,这是一个完美的例子。Python中的词典没有append方法。有两种方法可以添加到字典中,一种是命名新的键、值对,另一种是向dictionary.update()传递带键、值对的iterable。在代码中,您可以执行以下操作:

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.

相关问题 更多 >