首页 > 解决方案 > 访问区块链对象中的数据以获取钱包余额

问题描述

在尝试执行以下代码以访问区块链中的钱包余额时,我收到了错误:

TypeError: slice indices must be integers or None or have an index method

这是我使用的代码:

class Blockchain:

def __init__(self):
    self.chain = [] #stores the blockchain
    self.transactions = ["Plain as vanilla"]
    self.create_block(proof = 1, previous_hash="0") #helps with block creation
    self.nodes = set()
    

def create_block(self, proof, previous_hash):
    """ Used to make a block """
    block = {
        'index': len(self.chain) + 1,
        'timestamp': str(datetime.datetime.utcnow()),
        'proof': proof,
        'previous_hash': previous_hash,
        'data': self.transactions
    }
    self.transactions = []
    self.chain.append(block)
    return block        

self.balance = 0
chain = Blockchain.chain[]
i = 0
for x in range(len(chain)):
        if chain[i:"data":"reciver"] or chain[i:"data":"sender"] == publickey:
            io = 0
            for chain[i:"data":"reciver"] in chain[i:"data"]: #loop for iterating through the dictionary
                amount = int(chain[io:"data":"amount"])
                self.balance = self.balance + amount
                io = io + 1

        if chain[i:"data":"sender"] == publickey:
            amount = int(chain[i:"data":"amount"])
            self.balance = self.balance - amount
        
        i = i + 1
    if chain[-1] == 0:
        self.balance = 0
        return self.balance

该代码应该遍历列表中的字典中的字典以查找区块链中钱包的余额,编辑:我添加了如何在链上构建块的方法

标签: pythonpython-3.9

解决方案


你能提供错误信息吗?我看到您将“链”实例化为一个空列表,然后循环遍历它。

但是假设您只显示变量存在,要访问嵌套在此列表中的第二个字典中的字典,您应该使用:

chain[i]["data"]["receiver"]

推荐阅读