在字典中存储大数据的变量

2024-04-19 23:57:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以用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"]

这些print函数返回例如100行。现在我只想打印基于“已用大小”过滤器的前5个值。 我试着把这些值放在字典中,过滤出“使用的大小”的前五个值,但不确定如何在字典中使用它们。在

像这样的东西 {'vserver':(u'rcdn9-c01-sm-prod',),'usize':u'389120,'vname':(u'nprd_root_m01',),'aggr':(u'aggr1_n01',)}

任何其他的选项,比如namedtuples也很受欢迎。在

谢谢


Tags: nameinidforif字典attributesaggregate
2条回答

要获得按某个键排序的词典列表,请使用sorted。假设我有一个包含ab键的字典列表,并希望按照b元素的值对它们进行排序:

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}]

^{} 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(...)

相关问题 更多 >