Concatenating strings from dictionary tuples with different lengths

Viewed 62

I have a dictionary created with basketball player positions, with the key being the players name and the value being a tuple with their position(s). For example: {'Player1': ('SF', 'PF'), 'Player2': 'C', 'Player3': 'SG'}

I'm trying to concatenate each players position(s) with another string, but when I try to select the second value it ends up slicing the first value instead.

Is there a way to loop through the keys and each individual value for every player or do I need to make a nested loop for the conditions where the tuple has multiple values?

for k,v in player_position_dict.items():
    print(v[1])

creates an error because obviously certain positions won't have that index, so I'm wondering if there is there another loop I can use to test whether the value has multiple items? I've tried using len() but that either returns the string length if its a single position or the tuple length so that doesn't differentiate enough.

1 Answers

You could maybe use isinstance() before checking with len():

player_position_dict = {
    'Player1': ('SF', 'PF'),
    'Player2': 'C',
    'Player3': 'SG',
    'Player4': ('PG'),
}
some_string_to_concentate_with = 'some_string_to_concentate_with'
for player, position in player_position_dict.items():
    if isinstance(position, tuple):
        if len(position) > 1:
            print(f'{player} has multiple positions:')
            for pos in position:
                print(f'{some_string_to_concentate_with}_{pos}')
        elif len(position) == 1:
            print(f'{player} has one position:')
            print(f'{some_string_to_concentate_with}_{position[0]}')
    else:
        print(f'{player} has one position:')
        print(f'{some_string_to_concentate_with}_{position}')

Output:

Player1 has multiple positions:
some_string_to_concentate_with_SF
some_string_to_concentate_with_PF
Player2 has one position:
some_string_to_concentate_with_C
Player3 has one position:
some_string_to_concentate_with_SG
Player4 has one position:
some_string_to_concentate_with_PG
Related