Jump to content

aceder a key/value de uma lista de dicionários


jonhhy

Recommended Posts

Bom dia P@P,

# number of ...matches could obtained for len(goallist)
squad = []

soccerPl = {'nameSP': '', 'goalsbyGame':[], 'totalGoals': '', 'numMatches': ''} # name by input, goalsbygame append list, totalGoals cyclecounter and numMatches <- imply to obtain a len() function by a list (implícita de outra variável)

nextOne = ''

while True:
  soccerPl['nameSP'] = str(input(' Say soccerPlayer name? :  '))
  soccerPl['numMatches'] = int(input(' Say number of matches played? : ')) # vai derivar o número de chaves antes assim, devia por num varíável isolada.., pois consegue ser obtida a partir do len() da lista
  totalGoals = 0
  for i in range(0, soccerPl['numMatches']):
    print(f'Number of goals scored in match {i} :')
    soccerPl['goalsbyGame'].append(int(input('')))
    totalGoals += soccerPl['goalsbyGame'][i]

  soccerPl['totalGoals'] = totalGoals
  squad.append(soccerPl.copy())
  print('-='*25)
  nextOne = str(input('Do you want add more player to the squad? ')).strip().upper()
  if nextOne == 'N':
    break

print('The Squad player data ...')
print(f"{'No.':^5}  {'name':^9}  {'goals by match':<16} {'totalGoals':<12}  {'numMatches':<15} ")
for i in range(0,len(squad)):
  #for squad[i] in range (0squad
  print(f"{i+1:^5}  {squad[i]['nameSP']:^9} ) # squad[i]['nameSP']:^9}

 

não sei como squad[i]['nameSP'] aceder a este campos, isto é uma lista de dicionários,
 

Tenho de fazer 2 ciclos for para chegar a uma key do dicionário? e como?

Link to comment
Share on other sites

Alterei e coloquei por este tipo de for:

for player in squad:
  print(f"{i+1^5} {player['nameSP']:^9} {player['goalsbyGame']:<16} {player['totalGoals']:<12}  {player['numMatches']:<15} ")

 

contudo, não sei, como imprimir a lista que esta num item do dicionário com a key = 'goalsbyGame'

 

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-276755a840ae> in <module>
----> 1 print(f"{i+1^5} {player['nameSP']:^9} {player['goalsbyGame']:<16} {player['totalGoals']:<12}  {player['numMatches']:<15} ")

TypeError: unsupported format string passed to list.__format__

 

Link to comment
Share on other sites

23 minutos atrás, jonhhy disse:

Alterei e coloquei por este tipo de for:

for player in squad:
  print(f"{i+1^5} {player['nameSP']:^9} {player['goalsbyGame']:<16} {player['totalGoals']:<12}  {player['numMatches']:<15} ")

 

contudo, não sei, como imprimir a lista que esta num item do dicionário com a key = 'goalsbyGame'

 

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-276755a840ae> in <module>
----> 1 print(f"{i+1^5} {player['nameSP']:^9} {player['goalsbyGame']:<16} {player['totalGoals']:<12}  {player['numMatches']:<15} ")

TypeError: unsupported format string passed to list.__format__

 

Alterei esta parte do código:

(player['goalsbyGame'])[0]:<16

mas tenho resultados estranhos:

 

 Say soccerPlayer name? :  Telmo
 Say number of matches played? : 2
Number of goals scored in match 0 :
4
Number of goals scored in match 1 :
1
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Do you want add more player to the squad? Toninho
 Say soccerPlayer name? :  Toninho
 Say number of matches played? : 4
Number of goals scored in match 0 :
1
Number of goals scored in match 1 :
0
Number of goals scored in match 2 :
7
Number of goals scored in match 3 :
3
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Do you want add more player to the squad? n
The Squad player data ...
 No.     name     goals by match   totalGoals    numMatches      
  1     Telmo   4                5             2               
  2    Toninho  4                6             4               
-=-=-=

 

Edited by jonhhy
Link to comment
Share on other sites

for player in squad:
  print(f"{i+1:^5} {player['nameSP']:^13} {player['goalsbyGame']} {player['totalGoals']:<12}  {player['numMatches']:<15} ")
  player['goalsbyGame']=[]
  i += 1
  
  #deu 
  
  Say soccerPlayer name? :  Aníval
 Say number of matches played? : 2
Number of goals scored in match 0 :
7
Number of goals scored in match 1 :
1
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Do you want add more player to the squad? e
 Say soccerPlayer name? :  Juba
 Say number of matches played? : 4
Number of goals scored in match 0 :
2
Number of goals scored in match 1 :
3
Number of goals scored in match 2 :
4
Number of goals scored in match 3 :
5
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Do you want add more player to the squad? n
The Squad player data ...
 No.     name     goals by match   totalGoals    numMatches      
  1       Aníval      [7, 1, 2, 3, 4, 5] 8             2               
  2        Juba       [7, 1, 2, 3, 4, 5] 13            4     

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.