python将字典添加到现有字典-AttributeError:'dict'对象没有属性'append' [英] python add dictionary to existing dictionary - AttributeError: 'dict' object has no attribute 'append'

查看:339
本文介绍了python将字典添加到现有字典-AttributeError:'dict'对象没有属性'append'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试附加现有的JSON文件.当我覆盖整个JSON文件时,一切都将正常运行.我无法解决的问题在附录中.现在我完全茫然了.

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

这是我在 data ['hashlist'].append(entry)接收AttributeError的地方使用的代码:'dict'对象没有属性'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中的字典没有添加方法.有两种添加字典的方法,一种是命名一个新的键值对,或者将一个带有键的可迭代项值对传递给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}})

第一个可能更适合您尝试做的事情,因为第二个更适合您尝试添加大量键,值对的情况.

您可以在此处此处阅读更多有关字典的信息.

I'm trying to append an existing JSON file. When I overwrite the entire JSON file then everything works perfect. The problem that I have been unable to resolve is in the append. I'm completely at a loss at this point.

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

Here is the code that I'm using where data['hashlist'].append(entry) receive 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!')

解决方案

Usually python errors are pretty self-explanatory, and this is a perfect example. Dictionaries in Python do not have an append method. There are two ways of adding to dictionaries, either by nameing a new key, value pair or passing an iterable with key, value pairs to dictionary.update(). In your code you could do:

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

or:

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

The first one is probably superior for what you are trying to do, because the second one is more for when you are trying to add lots of key, value pairs.

You can read more about dictionaries in Python here.

这篇关于python将字典添加到现有字典-AttributeError:'dict'对象没有属性'append'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆