如何从字典返回某些键,值并打印新字典

时间:2020-10-09 12:35:28

标签: python

我的评估是,我需要在dict_studenten_cijfers词典中返回分数高于9的学生。现在,我正在打印新结果,但评估结果已返回。

我尝试过,但是当我尝试返回它时却无法正常工作,它变成了一个类(元组),但它也需要作为类字典打印出来。

评估是返回新的字典列表,并将字典作为dict类打印出来

def hoogvliegers(dict_studenten_cijfers):
    for key,value in dict_studenten_cijfers.items():
        if value >= 9.00:
            print(f"{key} heeft cijfer {value}.")

dict_studenten_cijfers = {
    'jonas': 9.2,
    'mustafa': 5.5,
    'mahmut': 6.0,
    'ahmed': 7.0,
    'ali': 6.0,
    'emma': 9.0,
    'klaas': 10.0,
    'pieter': 8.0,
    'peter': 7.0,
    'floris': 9.0,
    'jakob': 8.0,
    'mohammed': 10.0
}

hoogvliegers(dict_studenten_cijfers)

3 个答案:

答案 0 :(得分:1)

尝试

dict_studenten_cijfers = {
    'jonas': 9.2,
    'mustafa': 5.5,
    'mahmut': 6.0,
    'ahmed': 7.0,
    'ali': 6.0,
    'emma': 9.0,
    'klaas': 10.0,
    'pieter': 8.0,
    'peter': 7.0,
    'floris': 9.0,
    'jakob': 8.0,
    'mohammed': 10.0
}
gt_9 = [k for k,v in dict_studenten_cijfers.items() if v > 9]
print(gt_9)

输出

['jonas', 'klaas', 'mohammed']

答案 1 :(得分:1)

   public class BulletEntityRender extends MobRenderer<BulletEntity, BulletEntityModel<BulletEntity>>{
  protected static final ResourceLocation TEXTURE = new ResourceLocation(FortuneAndGlory.MODID, "textures/entity/bullet.png");

public BulletEntityRender(EntityRendererManager rendererManagerIn) {
    super(rendererManagerIn, new BulletEntityModel<>(), //shadowsize );
}

public void render(T entityIn, float entityYaw, float partialTicks, MatrixStack matrixStackIn, IRenderTypeBuffer bufferIn, int packedLightIn) {
    IVertexBuilder ivertexbuilder = net.minecraft.client.renderer.ItemRenderer.getBuffer(bufferIn, this.model.getRenderType(this.getEntityTexture(entityIn)), false, false);
    model.render(matrixStackIn, ivertexbuilder, packedLightIn, OverlayTexture.NO_OVERLAY, 1.0F, 1.0F,1.0F, 1.0F);
    super.render(entityIn, entityYaw, partialTicks, matrixStackIn, bufferIn, packedLightIn);
}

@Override
public ResourceLocation getEntityTexture(BulletEntity entity) {
    return TEXTURE;
    

}




}

此方法使用非常方便的“字典理解”,在其中循环遍历dict_studenten_cijfers = { 'jonas': 9.2, 'mustafa': 5.5, 'mahmut': 6.0, 'ahmed': 7.0, 'ali': 6.0, 'emma': 9.0, 'klaas': 10.0, 'pieter': 8.0, 'peter': 7.0, 'floris': 9.0, 'jakob': 8.0, 'mohammed': 10.0 } def hoogvliegers(dct): return {k:v for k,v in dct.items() if v>=9} hoogvliegers(dict_studenten_cijfers) 的每对key,value并返回字典,其唯一值是大于或等于9年级的那些值。

输出:

dct.items()

答案 2 :(得分:1)

您可以像这样使用dict理解,

def hoogvliegers(d):
    # .iteritems() for python 2.x, .items() for python 3.x
    filtered_dict = {k:v for k,v in d.iteritems() if v >= 9.0}
    return filtered_dict


dict_studenten_cijfers = {
    'jonas': 9.2,
    'mustafa': 5.5,
    'mahmut': 6.0,
    'ahmed': 7.0,
    'ali': 6.0,
    'emma': 9.0,
    'klaas': 10.0,
    'pieter': 8.0,
    'peter': 7.0,
    'floris': 9.0,
    'jakob': 8.0,
    'mohammed': 10.0
}

print(hoogvliegers(dict_studenten_cijfers))