I have a list which is j4. This list contains elements which have period and amount information. I need to seperate this j4 into two list which will show periods and amounts seperately. How can I do that?
j4 = [{'period': 1, 'amount': -2400.0},
{'period': 2, 'amount': -2400.0},
{'period': 3, 'amount': -2400.0},
{'period': 4, 'amount': -2400.0},
{'period': 5, 'amount': -2400.0},
{'period': 6, 'amount': -2400.0},
{'period': 7, 'amount': -2400.0},
{'period': 8, 'amount': -2400.0},
{'period': 9, 'amount': -2400.0},
{'period': 10, 'amount': -2400.0},
{'period': 11, 'amount': -2400.0},
{'period': 12, 'amount': -2400.0},
{'period': 13, 'amount': -2400.0},
{'period': 14, 'amount': -2400.0},
{'period': 15, 'amount': -2400.0},
{'period': 16, 'amount': -2400.0},
{'period': 17, 'amount': -2400.0},
{'period': 18, 'amount': -2400.0},
{'period': 19, 'amount': -2400.0},
{'period': 20, 'amount': -2400.0},
{'period': 21, 'amount': -2400.0},
{'period': 22, 'amount': -2400.0},
{'period': 23, 'amount': -2400.0},
{'period': 24, 'amount': -2400.0}]
CodePudding user response:
Use two list comprehensions:
j4_period = [d['period'] for d in j4]
j4_amount = [d['amount'] for d in j4]
is this what you are looking for?
CodePudding user response:
You can use these method
from operator import itemgetter
j4 = [{'period': 1, 'amount': -2400.0},
{'period': 2, 'amount': -2400.0},
{'period': 3, 'amount': -2400.0}]
period, amount = zip(*map(itemgetter("period", "amount"), j4))
or
period, amount = zip(*[ (i["period"], i["amount"]) for i in j4 ])
output
(1, 2, 3) (-2400.0, -2400.0, -2400.0)