Home > Software engineering >  How can I get the members of a dictionary in Python?
How can I get the members of a dictionary in Python?

Time:09-14

It is my code Python :

my_dict = {
    'Iran':[win_iran,loss_iran,draw_iran,diff_iran,point_iran],
    'Morocco':[win_marakesh,loss_marakesh,draw_marakesh,diff_marakesh,point_marakesh],
    'Portugal':[win_por,loss_por,draw_por,diff_por,point_por],
    'Spain':[win_spain,loss_spain,draw_spain,diff_spain,point_spain]}

I want to have this output:

Spain  wins: , loses: , draws: , goal difference: , points:
Iran  wins:1 , loses: , draws: , goal difference: , points:
Portugal  wins: , loses: , draws: , goal difference: , points:
Morocco  wins: , loses: , draws: , goal difference: , points:

please guide me.

CodePudding user response:

Loop over the dict's items, unpacking to useful names, then print the values as needed:

for country, (wins, losses, draws, diff, points) in my_dict.items():
    print(f'{country} wins: {wins}, losses: {losses}, draws: {draws}, '
          f'goal difference: {diff}, points: {points}')

Or less explicitly, but more succinctly, use str.format and use star-unpacking with implicit numbering so you don't repeat names as much:

for country, stats in my_dict.items():
    print(('{} wins: {}, losses: {}, draws: {}, goal difference: {}, '
           'points: {}').format(country, *stats))

CodePudding user response:

Straightforward:

for key,val in my_dict.items():
    print(f"{key}: wins:{val[0]}, losses:{val[1]}, draws:{val[2]}, goal difference:{val[3]}, points:{val[4]}")
  • Related