removing number of edges in python
<p>I was wondering if there is pythonic way to do this.</p>

<p>Suppose I list of dictionary:</p>

<pre><code>{'source': 338, 'target': 343, 'value': 0.667693}
{'source': 339, 'target': 342, 'value': 0.628195}
{'source': 340, 'target': 346, 'value': 0.529861}
{'source': 340, 'target': 342, 'value': 0.470139}
{'source': 341, 'target': 342, 'value': 0.762871}
{'source': 342, 'target': 349, 'value': 0.664869}
{'source': 343, 'target': 347, 'value': 0.513025}
{'source': 343, 'target': 344, 'value': 0.486975}
{'source': 344, 'target': 347, 'value': 0.536706}
{'source': 344, 'target': 349, 'value': 0.463294}
{'source': 345, 'target': 349, 'value': 0.546326}
{'source': 345, 'target': 346, 'value': 0.453674}
</code></pre>

<p>basically its an undirected graph. but its very messy. i want to clean it a bit.</p>

<p>So, I want to leave top 2 nodes which have most edges like in original format..</p>

<p>and for rest of the nodes... have atmost 5 edges attached to it.</p>

<p>I am just maintaining a dict with counts...
reverse sorting it..</p>

<p>then saving top 2 and going thru list again.. and removing the edges but checking for top 2 ones..</p>

<p>Is there a cleaner way to do this.</p>

<p>My buggy.. messy sample code:</p>

<pre><code>import json
from pprint import pprint
import operator
json_data=open('topics350_1.json')

data = json.load(json_data)
edges = data["links"]
node_count_dict = {}
super_nodes = 3
min_nodes = 5

for edge in edges:
    keys = [edge['source'], edge['target']]
    for key in keys:
        if key in node_count_dict:
            node_count_dict[key] +=1
        else:
            node_count_dict[key] = 1

sorted_nodes = sorted(node_count_dict.iteritems(), key=operator.itemgetter(1),reverse = True)           
#print sorted_nodes 
top_nodes = sorted_nodes[super_nodes]
final_node_count = {}
for key in sorted_nodes:
    final_node_count[key[0]] = 0
print final_node_count
link_list = []
for edge in edges:
    keys = [edge['source'], edge['target']]
    for key in keys:
        if key not in top_nodes:
            if final_node_count[key] &lt; min_nodes:
                link_list.append(edge)
print link_list




#print data['links']
</code></pre>
