[英]Access data in blockchain object for wallet balances
While trying to execute the code below to access the wallet balance in the blockchain, I'm getting the error:在尝试执行以下代码以访问区块链中的钱包余额时,出现错误:
TypeError: slice indices must be integers or None or have an index method
This is the code I use:这是我使用的代码:
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
the code is supposed to iterate through a dictionary inside a dictionary inside a list to find the balance of a wallet inside a blockchain, edit: I added the method of how a block is structured on the chain该代码应该遍历列表中字典中的字典以查找区块链中钱包的余额,编辑:我添加了如何在链上构建块的方法
Can you provide the error message?你能提供错误信息吗? I see that you instantiate "chain" as an empty list and then loops over it.
我看到您将“链”实例化为一个空列表,然后循环遍历它。
But assuming that you're only showing that the variable exists, to access a dictionary, nested inside a second dictionary within this list you should use:但是假设您只显示变量存在,要访问嵌套在此列表中的第二个字典中的字典,您应该使用:
chain[i]["data"]["receiver"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.