How do I retrieve multiple maximum values (or top N values) from each keys in my dictionary.
communities_dict = {1: "A","B","C","D","E","F","G","CB"
2: "H","I","J","K","L","M","N","XY"
3: "O","P","Q","R","S","T","U","GT"
4: "V","W","X","Y","Z","AB" "HH","FF",
5: "CD","EF","GH","IJ","KL","HG","FR","RR"}
# load the network graph
G = nx.read_adjlist("./data/networkgraph.csv", delimiter = ',')
# cluster the network graph
partition = community.best_partition(G)
# Get a set of the communities
communities = set(partition.values())
# Create a dictionary mapping community number to nodes within that community
communities_dict = {c: [k for k, v in partition.items() if v == c] for c in communities}
# Filter that dictionary to map community to the node of highest degree within the community
highest_degree = {k: max(v, key=lambda x: G.degree(x)) for k, v in communities_dict.items()}
This is the dictionary I get back from highest_degree is:
1: "A"
2: "I"
3: "Q"
4: "AB"
5: "CD"
But I would ideally want the top 3 nodes with the highest degree for each key instead the just one.
1: "A","B","C"
2: "I", "J","K"
3: "Q","P","Q"
4: "V","W","X"
5: "CD", "EF","GH"
CodePudding user response:
Since you want the 3
nodes with highest degree you can use sorted
and then slice your new list with [-3:]
to get the last 3 elements. In your example this would look like:
highest_degree = {k: sorted(v, key=G.degree)[-3:] for k, v in communities_dict.items()}
CodePudding user response:
For multiple values of each key you must use [] for your values. Your code has some syntax errors like You have not used a comma to separate the previous values from the next key. your code must be like that:
'''
dict = {1: ["A","B","C","D","E","F","G","CB"],
2: ["H","I","J","K","L","M","N","XY"],
3: ["O","P","Q","R","S","T","U","GT"],
4: ["V","W","X","Y","Z","AB" "HH","FF"],
5: ["CD","EF","GH","IJ","KL","HG","FR","RR"]}
'''