Finding the elements with the most neighbors I have a sample list which contains nodes and their neighbors, if they have any. The task is to find the node which have the highest number of neighbors.

neigh = [['A'],['A','B'],['A','C'],['B','D'],['C','A']]


The input is undirected. Meaning that ['A', 'B'] are neighbors. While ['A'] doesn't have any neighbors since it has no other value within its own list. If a sublist has 2 elements, then they are neighbors. Otherwise they are not neighbors.

My solution is below, it has a lot of if-else statements. Is there a more elegant way to solve this?

def find_neighbors(neigh):
    d = {}
    for i in neigh:
        if i:
                if len(i)==2:
                    if i[0] in d.keys():
                        d[i[0]] +=1.0
                    else:
                        d[i[0]] = 1.0

                    if i[1] in d.keys():
                        d[i[1]] +=1.0
                    else:
                        d[i[1]] = 1.0

    max = 0
    for i,j in d.items():
        if j &gt; max:
            max = j
    return [i for i, j in d.items() if j == max]

find_neighbors(neigh)
This checks if there is a neighbor of an element and if so, adds it to the count. 

import operator 
def find_max_letter_in_array(neighborhood):
  all_neighbors_with_count = {}
  for neighbor_set in [pair_of_neighbors for pair_of_neighbors in neighborhood if len(pair_of_neighbors) &gt; 1]:
    for neighbor in neighbor_set:
      all_neighbors_with_count.update({neighbor[0]: 1 if neighbor[0] not in all_neighbors_with_count else all_neighbors_with_count[neighbor[0]]+ 1})

  #return all_neighbors_with_count
  return max(all_neighbors_with_count.items(), key=operator.itemgetter(1))[0]


neigh = [['A'],['A','B'],['A','C'],['B','D'],['C','A']]
print(find_max_letter_in_array(neigh))

output: 
#{'A': 3, 'B': 2, 'C': 2, 'D': 1}
A



You can loop over lists with conditions in them so that you only iterate over items you actually need 


for each_element in [element for element in list if len(element) &gt; 1]:



Another important part is, you can use dict.update to do both insert and update. 
You can use the if statement while doing the assignment of a value  as well


x = y if something_is_true else 



At the end, using the operator.max, you can simply your code to get the max element key from dictionary based on all keys' values.


Hope it helps in how you can compress your code.