Home > Mobile >  Transforming tuple to a desired structure
Transforming tuple to a desired structure

Time:10-27

Below is a tuple:

import ast

data = (('Jeff Celebration',
  '{"2010-09-02": {"Possibility": 3, "Confidence":93}, "2011-09-01": {"Possibility": 3, "Confidence":86}}'),
 ("Queens Bday",
  '{"2010-02-18": {"Possibility": 2, "Confidence":88}, "2011-02-17": {"Possibility": 2, "Confidence":88}}'))

This is where I am :

data = {i[0]: {key:val.get('Possibility') for key, val in ast.literal_eval(i[1]).items()} for i in data}

How do I use the "Possibility" value to iterate and add to subscript of event name?

Expected Output:

data = {'event': ['Jeff Celebration_1', 'Jeff Celebration_2', 'Jeff Celebration_3', 'Jeff Celebration_1', 'Jeff Celebration_2', 'Jeff Celebration_3', 'Queens Bday_1', 'Queens Bday_2', 'Queens Bday_1', 'Queens Bday_2'], 
        'keys': ['2010-09-02', '2010-09-03', '2010-09-04', '2011-09-01', '2011-09-02', '2011-09-03', '2010-02-18', '2010-02-19', '2011-02-17', '2011-02-18']}

EDIT: Each event need to be repeated 'Possibility' Time. So, Jeff Celebration has 3 entry in the output.

CodePudding user response:

You can use below code get the desired output

import ast
from datetime import datetime, timedelta

data = (('Jeff Celebration',
  '{"2010-09-02": {"Possibility": 3, "Confidence":93}, "2011-09-01": {"Possibility": 3, "Confidence":86}}'),
 ("Queens Bday",
  '{"2010-02-18": {"Possibility": 2, "Confidence":88}, "2011-02-17": {"Possibility": 2, "Confidence":88}}'))

event = []
keys = []

for event_name, info_str in data:
    info = ast.literal_eval(info_str)
    for date, conf in info.items():
        for index in range(conf["Possibility"]):
            event.append(f'{event_name}_{index 1}')
            new_date = datetime.strptime(date, "%Y-%m-%d")   timedelta(days=index)
            keys.append(new_date.strftime("%Y-%m-%d"))

print({'event': event, 'keys': keys})

output

{
  'event': ['Jeff Celebration_1', 'Jeff Celebration_2', 'Jeff Celebration_3', 'Jeff Celebration_1', 'Jeff Celebration_2', 'Jeff Celebration_3', 'Queens Bday_1', 'Queens Bday_2', 'Queens Bday_1', 'Queens Bday_2'],
  'keys': ['2010-09-02', '2010-09-03', '2010-09-04', '2011-09-01', '2011-09-02', '2011-09-03', '2010-02-18', '2010-02-19', '2011-02-17', '2011-02-18']
}

CodePudding user response:

First of all, you are using the ast module here, when the json module could be simpler to use. Anyway from your intermediary data, you could:

  • build an iterable of pairs (event, key)
  • zip it
  • and build you final data from that

Possible code

lst = tuple(zip(*((event   '_'   str(1   occur), key)
   for event, d in data.items()
   for key, possibility in d.items()
   for occur in range(possibility)
   )))
data = {'events': list(lst[0]), 'keys': list(lst[1])}
  • Related