0

I have a python tuple with the following format:

({'day': '03/06', 'stock': 10}, {'day': '04/06', 'stock': 12}, {'day': '05/06', 'stock': 5})

I would like to get a comma separated string with each key pair:

days = '03/06, 04/06, 05/06'
stocks = '10, 12, 5'

I'm using a loop with range and len to extract the values, but I think it's not optimal.

I've tried this and this suggestion but I don't get the results I'm looking for. Is there a better way to get these values without a loop?

Thanks

nfn
  • 39
  • 6

2 Answers2

2

Using a list comprehension:

inp = ({'day': '03/06', 'stock': 10}, {'day': '04/06', 'stock': 12}, {'day': '05/06', 'stock': 5})
days = ', '.join([x['day'] for x in inp])
stocks = ', '.join([str(x['stock']) for x in inp])
print(days)    # 03/06, 04/06, 05/06
print(stocks)  # 10, 12, 5
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

You can extract values of the desired keys from the input sequence of dicts by mapping the sequence to operator.itemgetter, and then convert the sequence of day-stock pairs into two sequences of values for days and stocks using zip.

Assuming that your input sequence is stored in data:

from operator import itemgetter

days, stocks = zip(*map(itemgetter('day', 'stock'), data))
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Is there a way to output a result like this using your method: "03/06", "04/06", "05/06"? Thanks – nfn Jun 09 '21 at 18:37