0

I can print variables in python.

for h in jl1["results"]["attributes-list"]["volume-attributes"]:
        state = str(h["volume-state-attributes"]["state"])
        if aggr in h["volume-id-attributes"]["containing-aggregate-name"]:
                if state == "online":

print(h["volume-id-attributes"]["owning-vserver-name"]),
print(' '),
print(h["volume-id-attributes"]["name"]),
print(' '),
print(h["volume-id-attributes"]["containing-aggregate-name"]),
print(' '),
print(h["volume-space-attributes"]["size-used"]

These print function returns for example 100 lines. Now I want to print only top 5 values based on filter of "size-used". I am trying to take these values in dictionary and filter out top five values for "size-used" but not sure how to take them in dictionary.

Some thing like this {'vserver': (u'rcdn9-c01-sm-prod',), 'usize': u'389120', 'vname': (u'nprd_root_m01',), 'aggr': (u'aggr1_n01',)}

Any other options like namedtuples is also appreciated.

Thanks

2 Answers2

0

To get a list of dictionaries sorted by a certain key, use sorted. Say I have a list of dictionaries with a and b keys and want to sort them by the value of the b element:

my_dict_list = [{'a': 3, 'b': 1}, {'a': 1, 'b': 4}, {'a': 4, 'b': 4},
                {'a': 2, 'b': 7}, {'a': 2, 'b': 4.3}, {'a': 2, 'b': 9}, ]


my_sorted_dict_list = sorted(my_dict_list, key=lambda element: element['b'], reverse=True)
# Reverse is set to True because by default it sorts from smallest to biggest; we want to reverse that

# Limit to five results
biggest_five_dicts = my_sorted_dict_list[:5]

print(biggest_five_dicts)  # [{'a': 2, 'b': 9}, {'a': 2, 'b': 7}, {'a': 2, 'b': 4.3}, {'a': 1, 'b': 4}, {'a': 4, 'b': 4}]
  • my first question is how to create a dictionary from variables. Like this one "{'vserver': (u'rcdn9-c01-sm-prod',), 'usize': u'389120', 'vname': (u'nprd_root_m01',), 'aggr': (u'aggr1_n01',)}" – user3114051 Jun 14 '17 at 01:55
0

heapq.nlargest is the obvious way to go here:

import heapq

interesting_dicts = ... filter to keep only the dicts you care about (e.g. online dicts) ...

for large in heapq.nlargest(5, interesting_dicts,
                            key=lambda d: d["volume-space-attributes"]["size-used"]):
    print(...)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • my first question is how to create a dictionary from variables. Like this one "{'vserver': (u'rcdn9-c01-sm-prod',), 'usize': u'389120', 'vname': (u'nprd_root_m01',), 'aggr': (u'aggr1_n01',)}" – user3114051 Jun 14 '17 at 01:56