This is an easy tip, but an extremely useful feature of Python.
Let's take the following sample list:
my_list = ['a', 'b','c']
I want to put each list element into their own variable, you could write a for loop or iterate through the list to create a variable for each element.
a, b, c = my_list
That's it!
This is all cool and so on, but want to see it in action?
Let's grab the latest block on the Steem blockchain.
Full Block Displayed Here
First, we want to get just the transactions in the block.
(I am going to skip some for loops and just focus on an individual transaction)
transactions = block['transactions']
If we look at the first transaction we get something like this:
{
'ref_block_num': 50957,
'ref_block_prefix': 355189199,
'expiration': '2018-04-27T18:09:24',
'operations': [
[
'vote',
{
'voter': 'loradavis',
'author': 'veseloff',
'permlink': 'the-deal-coin-innovative-solution -for-business-lending',
'weight': 10000
}
]
],
'extensions': [
],
'signatures': [
'20198cf4469c494880329cc9966fa070e022ab134e09f03f9d9213809f8a4ac207744c79c8dbbdf4976ac0a330977df97ba534d764c45b9cf87ea37f461f075a15 '
]
}
We are concerned with the operations section.
operations = transaction['operations']
This will give us all operations for a particular transaction. This is typically only one operation like this:
[
[
'vote',
{
'voter': 'loradavis',
'author': 'veseloff',
'permlink': 'the-deal-coin-innovative-solution-for-business-lending',
'weight': 10000
}
]
]
If you look carefully you will see there are two pieces of the initial list, the operation type, and the operation. Let's use destructuring here to break this up quickly and easily from the first (and likely only) operation.
op_type, op = operations[0]
print(op_type)
>> 'vote`
print(op)
>> {'voter': 'loradavis', 'author': 'veseloff', 'permlink': 'the-deal-coin-innovative-solution-for-business-lending', 'weight': 10000}
You can break down the operation using destructuring as well if you wanted to.
{'voter': 'loradavis', 'author': 'veseloff', 'permlink': 'the-deal-coin-innovative-solution-for-business-lending', 'weight': 10000}
voter, author, permlink, weight = op
Destructuring is a powerful Python tool that when used properly can make your code easier to read and easier to write. It works best for data sets that have only a few elements and wouldn't work well destructuring into 10-20+ variables. When working on with data sets with 2-5 elements, it's a really nice tool to have in your toolbox.