Reputation: 1170
I have sorted map that stores keys and values of a dict:
def sorted_map(map):
ms = sorted(map.iteritems(), key=lambda (k,v): (-v,k))
return ms
It stores the network nodes as keys, and their degrees as values – the output is like this:
for line in ms:
print line
('Node n', 11)
('Node n+1', 11)
('Node n+2', 11)
Values range from ~ 1000 through 0. I need to only select those nodes (keys) that have a value of higher/equal to 10. And preferably store them into a new dict (key:value). Is there a way to do it?
Upvotes: 0
Views: 118
Reputation: 323
dict comprehension from Padraic is a better solution, but just to see what is out there you can use filter and dict functions:
def sorted_map(dictionary):
ms = sorted(dictionary.iteritems(), key=lambda (k, v): (-v, k))
return ms
star_map = {
'Node 1': 11,
'Node 2': 12,
'Node 3': 9,
}
filtered = filter(lambda x: x[1] >= 10, sorted_map(star_map))
print(dict(filtered))
Note: You should not use map
as a variable name because this is a built-in function.
Upvotes: 1
Reputation: 180482
Just create a new dict from your original dict items, keeping key/value pairings that have a value >= 10
d = {1:23,2:20,3:10,4:9,5:1}
print({k:v for k,v in d.items() if v >=10})
{1: 23, 2: 20, 3: 10}
If you just want a new dict sorting is not required.
Upvotes: 2