M
M
Master Ruby2021-11-12 16:53:51
Python
Master Ruby, 2021-11-12 16:53:51

How to transfer data from one dictionary to another dictionary or array?

There is the following list with a dictionary:

odds = [
    {'Date': '2021-11-20T12:30:00Z', 'Odds': 4.55, 'Team': 'Leicester City'},
    {'Date': '2021-11-28T14:00:00Z', 'Odds': 1.47, 'Team': 'Leicester City'},
    {'Date': '2021-11-20T15:00:00Z', 'Odds': 2.75, 'Team': 'Burnley'},
    {'Date': '2021-11-28T14:00:00Z', 'Odds': 3.55, 'Team': 'Burnley'},
]

How can I transfer data from the dictionary so that there are no repeated team names, but keffs remain, for example:
{'Date': '2021-11-20T12:30:00Z', 'Odds1': 4.55,  'Odds2': 1.47, 'Team': 'Leicester City'},

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
aRegius, 2021-11-12
@Dunaevlad

defaultdict
Try this:

temp_data = defaultdict(list)

for data in odds:
    temp_data[data['Team']].append((data['Odds'], data['Date']))

temp_data = {key: zip(*value) for key, value in temp_data.items()}
new_data = [dict(Team=team, Odds=odds, Date=date) for team, (odds, date) in temp_data.items()]

M
MaratPetrov96, 2021-11-12
@MaratPetrov96

odds = [
    {'Date': '2021-11-20T12:30:00Z', 'Odds': 4.55, 'Team': 'Leicester City'},
    {'Date': '2021-11-28T14:00:00Z', 'Odds': 1.47, 'Team': 'Leicester City'},
    {'Date': '2021-11-20T15:00:00Z', 'Odds': 2.75, 'Team': 'Burnley'},
    {'Date': '2021-11-28T14:00:00Z', 'Odds': 3.55, 'Team': 'Burnley'},
]

new=[]
for i in odds:
    new.append(dict())
    for k,v in i.items():
        new[-1][k]=v

I hope you understand the essence
(I edited the answer. I'm sorry, I'm getting used to writing code here, please delete comments with errors)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question