M
M
Master Ruby2021-11-12 14:40:25
Python
Master Ruby, 2021-11-12 14:40:25

How to find the desired value in the dictionary?

There are two dictionaries:

teams = [
    {'team': 'Leicester City ', 'id': 1007732583, 'date': '2021-11-20T12:30:00Z'},
    {'team': 'Leicester City ', 'id': 1007732570, 'date': '2021-11-28T14:00:00Z'},
    {'team': 'Burnley ', 'id': 1007732584, 'date': '2021-11-20T15:00:00Z'},
    {'team': 'Burnley ', 'id': 1007732573, 'date': '2021-11-28T14:00:00Z'},
    {'team': ' Manchester United', 'id': 1007732585, 'date': '2021-11-20T15:00:00Z'},
    {'team': ' Manchester United', 'id': 1007732572, 'date': '2021-11-28T16:30:00Z'},
]

odds = [
    {'label': '1', 'team': 'Leicester City', 'odds': 4.55},
    {'label': 'X', 'team': 'draw', 'odds': 3.65},
    {'label': '2', 'team': 'Chelsea', 'odds': 1.79},
    {'label': '1', 'team': 'Leicester City', 'odds': 1.47},
    {'label': 'X', 'team': 'draw', 'odds': 4.75},
]

for i in teams:
    for j in odds:
        if i['team'] == j['team']:
            print(i['team'], j['odds'])  # => None

What is the best way to look up the values ​​of the teams['team'] key from the teams dictionary in the odds dictionary to get data from odds['odds']. Those. if teams['team'](Leicester City) is in odds, then get all values ​​of odds['odds'].

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wispik, 2021-11-12
@Dunaevlad

Yes, you have a problem with spaces in your code (at the beginning and end of the line), but I would do this:
1. I would collect all the unique names of clubs in a variable: 2. Then I would look for coefficients (this way there will be fewer loop iterations):
_teams = set([x['team'].strip() for x in teams])

for team in _teams:
  _odds = [x['odds'] for x in filter(lambda x: x['team'] == team, odds)]
  print(team, _odds)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question