# Python – Paired Neighbors to Adjacency Dictionary

• Last Updated : 22 Apr, 2020

Sometimes while working with Python pairs, we can have problem in which pairs represent the neighbours and we need to compute neighbors of each element. This kind of problem is quite common in competitive programming and while working with graphs. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop
This is one of the approach that can be applied to solve this problem. In this, we preassume the required keys and construct the dictionary with empty lists, and iterate the pair list appending the values.

 `# Python3 code to demonstrate working of ``# Paired Neighbours to Adjacency Dictionary``# Using loop`` ` `# initializing list``test_list ``=` `[(``1``, ``2``), (``4``, ``5``), (``1``, ``3``), (``3``, ``4``), (``5``, ``6``), (``6``, ``2``)]`` ` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))`` ` `# Paired Neighbours to Adjacency Dictionary``# Using loop``res ``=` `{``1``: [], ``2``: [], ``3``: [], ``4``: [], ``5``: [], ``6``: []}``for` `sub ``in` `test_list:``    ``res[sub[``0``]].append(sub[``1``])``    ``res[sub[``1``]].append(sub[``0``])``     ` `# printing result ``print``(``"The Neighbours Paired Dictionary : "` `+` `str``(res)) `

Output :

The original list is : [(1, 2), (4, 5), (1, 3), (3, 4), (5, 6), (6, 2)]
The Neighbours Paired Dictionary : {1: [2, 3], 2: [1, 6], 3: [1, 4], 4: [5, 3], 5: [4, 6], 6: [5, 2]}

Method #2 : Using `defaultdict()` + loop
The combination of above functions can also be used to solve this problem. In this, we initialize the dictionary as default set. The eliminates the problem of duplicacy and also gives more flexibility regarding more undetermined node values.

 `# Python3 code to demonstrate working of ``# Paired Neighbours to Adjacency Dictionary``# Using defaultdict() + loop``from` `collections ``import` `defaultdict`` ` `# initializing list``test_list ``=` `[(``1``, ``2``), (``4``, ``5``), (``1``, ``3``), (``3``, ``4``), (``5``, ``6``), (``6``, ``2``)]`` ` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))`` ` `# Paired Neighbours to Adjacency Dictionary``# Using defaultdict() + loop``res ``=` `defaultdict(``set``)``for` `sub ``in` `test_list:``    ``res[sub[``0``]].add(sub[``1``])``    ``res[sub[``1``]].add(sub[``0``])``     ` `# printing result ``print``(``"The Neighbours Paired Dictionary : "` `+` `str``(``dict``(res))) `

Output :

The original list is : [(1, 2), (4, 5), (1, 3), (3, 4), (5, 6), (6, 2)]
The Neighbours Paired Dictionary : {1: {2, 3}, 2: {1, 6}, 3: {1, 4}, 4: {3, 5}, 5: {4, 6}, 6: {2, 5}}

My Personal Notes arrow_drop_up