Home > Back-end >  Dictionaries: iteration, indexing
Dictionaries: iteration, indexing

Time:12-27

I am having a problem to iterate through a Dictionary without casting the Dictionary into a List.

The exercise is the following:

"Let D be a dictionary whose keys are soccer teams and whose values is the “strength” of the team.

Fill in D with values at your own will.

Write a function randomChampion(D, k) that picks up at random k pairs of distinct elements in D and simulates a match between them.

If one of the teams in the pair has strength greater than the other it gets 2 points. If the teams have equal strength both of them get 1 point.

The function will return a new dictionary C whose keys are the teams and whose values are the final score at the end of the “championship” ".

D={"Inter": 10, "Juve":9, "Milan":7, "Napoli":10, "Fiorentina":7, "Lazio":9}

def randomChampion(D):
    
    championship={}
    
    for x in D.values():
        for y in D.values():
            if x>y:
                championship=2
            elif x==y:
                championship=1
    return print(championship)

CodePudding user response:

To iterate through the dictionary without casting it to a list, you can use the items() method of the dictionary

https://docs.python.org/3/library/stdtypes.html#dict.items

CodePudding user response:

Try this:

import random 
def randomChampion(data,k):
  result = {}
  teams = list(D)
  matching_pairs = random.sample(teams,k*2)
  for i in range(0,len(matching_pairs),2):
    team1 = str(matching_pairs[i])
    team2 = str(matching_pairs[i 1])
    if D[team1]>D[team2]:
        result[team1]=2
        result[team2]=0
    elif D[team1]==D[team2]:
        result[team1]=1
        result[team2]=1
    else:
        result[team2]=2
        result[team1]=0
  return result
  • Related