Home > Enterprise >  FOR loop - sort by first element in a list
FOR loop - sort by first element in a list

Time:09-22

I get the following data

{'Value': ['A000453', 'Product AB', 5.0]}
{'Value': ['A000201', 'Product UV', 10.0]}
{'Value': ['A000900', 'Product XY', 2.0]}

which I can output in a loop, as follows:

for i in x['data']:
    print('Order:', i['Value'][0])
    print('Product:', i['Value'][1])
    print('Amount:', int(i['Value'][2]))

Is there any way to sort the output within the loop by the first value?

So that it looks like this at the end:

Order: A000201
Product: Product UV
Amount: 10

Order: A000453
Product: Product AB
Amount: 5

Order: A000900
Product: Product XY
Amount: 2

Thank you very much.

CodePudding user response:

You can achieve that by using sort with a custom key. For example:

x = [
    {'Value': ['A000453', 'Product AB', 5.0]},
    {'Value': ['A000201', 'Product UV', 10.0]},
    {'Value': ['A000900', 'Product XY', 2.0]}
    ]
x.sort(key= lambda x: x['Value'][0])

for i in x:
    print('Order:', i['Value'][0])
    print('Product:', i['Value'][1])
    print('Amount:', int(i['Value'][2]))

The output will be:

Order: A000201
Product: Product UV
Amount: 10

Order: A000453
Product: Product AB
Amount: 5

Order: A000900
Product: Product XY
Amount: 2

CodePudding user response:

in this way you can sort the list by first element:

data.sort(key=lambda x: x['Value'][0])

CodePudding user response:

Without a key function:

data = [
    {'Value': ['A000453', 'Product AB', 5.0]},
    {'Value': ['A000201', 'Product UV', 10.0]},
    {'Value': ['A000900', 'Product XY', 2.0]},
]

for order, product, amount in sorted(d['Value'] for d in data):
    print('Order:', order)
    print('Product:', product)
    print('Amount:', int(amount))
    print()

CodePudding user response:

Try operator.itemgetter:

from operator import itemgetter as ig
for x, y, z in sorted(map(ig('Value'), a), key=ig(0)):
    print('Order:', x)
    print('Product:', y)
    print('Amount:', int(z))
  • Related