'How to print separately this type of pair? [closed]

adjacency_list = {
    'A': [('B', 8), ('C', 2), ('D', 14)],
    'B': [('D', 21)],
    'C': [('E', 19)],
    'D': [('E',17), ('F', 13), ('C', 25)],
    'E': [('G', 9), ('F', 5)],
    'F': [('G', 1)]
}
row = adjacency_list.get('F')
for pair in row:
    print(pair)

I have this list, I want to print pair value separately, like CPP. I want to print pair.first and then pair.second. Which will print 'G' first and then 1 instead of printing ('G', 1) together.
How can I do this?



Solution 1:[1]

Simple unpacking seems to be enough:

>>> for pair in row:
...     print(*pair)
...
G 1

Solution 2:[2]

seems like you have some key value pairs?

adjacency_list = {
    'A': [('B', 8), ('C', 2), ('D', 14)],
    'B': [('D', 21)],
    'C': [('E', 19)],
    'D': [('E',17), ('F', 13), ('C', 25)],
    'E': [('G', 9), ('F', 5)],
    'F': [('G', 1)]
}
row = adjacency_list.get('F')
for key,value in row:
    print("Key: " + str(key) + " Value: " + str(value))

Solution 3:[3]

I usually do it like this:

adjacency_list = {
    'A': [('B', 8), ('C', 2), ('D', 14)],
    'B': [('D', 21)],
    'C': [('E', 19)],
    'D': [('E',17), ('F', 13), ('C', 25)],
    'E': [('G', 9), ('F', 5)],
    'F': [('G', 1)]
}
row = adjacency_list.get('F')
for (k, v) in row:
    print(f'{k}{v}')

In the for loop you can name the elements of the pair, and then print using f-strings for string interpolation using the names you bound the elements of the pair to.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mechanic Pig
Solution 2 Shawn Ramirez
Solution 3 Matt S