I've the following graph:
import networkx as nx
import matplotlib.pyplot as plt
g = nx.Graph()
g.add_edge("A","B")
g.add_edge("A","C")
g.add_edge("A","D")
g.add_edge("B","F")
g.add_edge("B","G")
g.add_edge("B","H")
g.add_edge("I","F")
g.add_edge("I","k")
nx.draw(g,with_labels=True)
plt.show()
g.nodes(data=True)
g.edges(data=True)
I then calculated the shortest distance between all nodes as follows:
p = dict(nx.shortest_path_length(g))
p
Outputs:
{'A': {'A': 0, 'B': 1, 'D': 1, 'C': 1, 'G': 2, 'H': 2, 'F': 2, 'I': 3, 'k': 4},
'B': {'B': 0, 'G': 1, 'H': 1, 'A': 1, 'F': 1, 'D': 2, 'C': 2, 'I': 2, 'k': 3},
'C': {'C': 0, 'A': 1, 'B': 2, 'D': 2, 'G': 3, 'H': 3, 'F': 3, 'I': 4, 'k': 5},
'D': {'D': 0, 'A': 1, 'B': 2, 'C': 2, 'G': 3, 'H': 3, 'F': 3, 'I': 4, 'k': 5},
'F': {'F': 0, 'B': 1, 'I': 1, 'k': 2, 'H': 2, 'G': 2, 'A': 2, 'D': 3, 'C': 3},
'G': {'G': 0, 'B': 1, 'H': 2, 'A': 2, 'F': 2, 'D': 3, 'C': 3, 'I': 3, 'k': 4},
'H': {'H': 0, 'B': 1, 'G': 2, 'A': 2, 'F': 2, 'D': 3, 'C': 3, 'I': 3, 'k': 4},
'I': {'I': 0, 'k': 1, 'F': 1, 'B': 2, 'G': 3, 'H': 3, 'A': 3, 'D': 4, 'C': 4},
'k': {'k': 0, 'I': 1, 'F': 2, 'B': 3, 'G': 4, 'H': 4, 'A': 4, 'D': 5, 'C': 5}}
How can I extract all numerical values only (length=81) and store them in a list for further manipulation? I've tried list(p) but didn't work.
CodePudding user response:
Since you are dealing with a nested dictionary, one way to do it would be to iterate through the values of the first layer of your nested dictionary and append the values of the second layer of your dictionary to a list. You can then flatten your list to get the output you want.
See code below:
d={'A': {'A': 0, 'B': 1, 'D': 1, 'C': 1, 'G': 2, 'H': 2, 'F': 2, 'I': 3, 'k': 4},
'B': {'B': 0, 'G': 1, 'H': 1, 'A': 1, 'F': 1, 'D': 2, 'C': 2, 'I': 2, 'k': 3},
'C': {'C': 0, 'A': 1, 'B': 2, 'D': 2, 'G': 3, 'H': 3, 'F': 3, 'I': 4, 'k': 5},
'D': {'D': 0, 'A': 1, 'B': 2, 'C': 2, 'G': 3, 'H': 3, 'F': 3, 'I': 4, 'k': 5},
'F': {'F': 0, 'B': 1, 'I': 1, 'k': 2, 'H': 2, 'G': 2, 'A': 2, 'D': 3, 'C': 3},
'G': {'G': 0, 'B': 1, 'H': 2, 'A': 2, 'F': 2, 'D': 3, 'C': 3, 'I': 3, 'k': 4},
'H': {'H': 0, 'B': 1, 'G': 2, 'A': 2, 'F': 2, 'D': 3, 'C': 3, 'I': 3, 'k': 4},
'I': {'I': 0, 'k': 1, 'F': 1, 'B': 2, 'G': 3, 'H': 3, 'A': 3, 'D': 4, 'C': 4},
'k': {'k': 0, 'I': 1, 'F': 2, 'B': 3, 'G': 4, 'H': 4, 'A': 4, 'D': 5, 'C': 5}}
list_val=[]
[list_val.append(list(value.values())) for value in d.values()]
list_val_flat=sum(list_val,[]) #flatten list
print(list_val_flat)
And the output gives:
[0, 1, 1, 1, 2, 2, 2, 3, 4, 0, 1, 1, 1, 1, 2, 2, 2, 3, 0, 1, 2, 2, 3, 3, 3, 4, 5, 0, 1, 2, 2, 3, 3, 3, 4, 5, 0, 1, 1, 2, 2, 2, 2, 3, 3, 0, 1, 2, 2, 2, 3, 3, 3, 4, 0, 1, 2, 2, 2, 3, 3, 3, 4, 0, 1, 1, 2, 3, 3, 3, 4, 4, 0, 1, 2, 3, 4, 4, 4, 5, 5]
