如何从 python 字典中查找 N% 的键和值

How to find N% of key and values from a python dictiobary

我有一本 python 字典:-

x = {"a": 1, "b": 2, "c": 3, "d":4, "e": 5, "f": 6}

我只想找到字典返回给我的 N% 的键和值。 例如,从这本字典中,我只想获取 50% 的键值对。 所以我的输出应该是:-

{"a": 1, "b": 2, "c": 3}

有什么帮助吗?

首先计算给定百分比对应的计数,并确保它是一个整数。您还可以使用 floorceil 函数四舍五入为整数。然后你可以使用 enumerate 如下

x = {"a": 1, "b": 2, "c": 3, "d":4, "e": 5, "f": 6}

percent = 50

count = int(percent*len(x)/100)

output = {}
for i,key in enumerate(x.keys(),1):
    if(i>count):
        break
    output[key] = x[key]

print(output)

如果要随机选择 python 字典中 N% 的元素,可以使用 random 模型。

import random

x = {"a": 1, "b": 2, "c": 3, "d":4, "e": 5, "f": 6}

percent = 50

count = int(percent*len(x)/100)

# get list of all the keys in the  dictionary and convert it to a list
keys = x.keys()
keys = list(keys)

# use random.choices to choice randomly count element from the keys list
new_keys = random.choices(keys, k=count)

output = {}
for key in new_keys:
    output[key] = x[key]

print(output)

你会得到输出

{'d': 4, 'a': 1, 'c': 3}