[英]Replace value of a dictionary from an other dictionary based on value and key
我是 Python 的初学者,所以答案可能很简单,我发现很多信息可以根据其他字典值更新字典值,但总是使用相同的键。
我有两本词典。 一种是:
global_informations = {"id": "ID_PRODUIT",
"name": "NOM_PRODUIT",
"type_fdes": "PRODUIT_TYPE",
"nb_refs_commerciales": "NB_REF_COMM",
"quantite_unit_fonct": "QUANTITE_UF",
"type_unit_fonct": "ID_UNIT_UF",
"duree_vie": "DVT",
"carbon_biogenique": "CARBONE_BIO"
}
在这个目录中, PRODUIT_TYPE
是一个int (1,2 或 3)我想根据这个字典替换这个值:
type_fdes_dictionary = {1: "individuel",
2: "collectif",
3: "defaut"
}
例如,如果我有:
global_informations = {"id": "ID_PRODUIT",
"name": "NOM_PRODUIT",
"type_fdes": 1,
"nb_refs_commerciales": "NB_REF_COMM",
"quantite_unit_fonct": "QUANTITE_UF",
"type_unit_fonct": "ID_UNIT_UF",
"duree_vie": "DVT",
"carbon_biogenique": "CARBONE_BIO"
}
我想:
global_informations = {"id": "ID_PRODUIT",
"name": "NOM_PRODUIT",
"type_fdes": "individuel",
"nb_refs_commerciales": "NB_REF_COMM",
"quantite_unit_fonct": "QUANTITE_UF",
"type_unit_fonct": "ID_UNIT_UF",
"duree_vie": "DVT",
"carbon_biogenique": "CARBONE_BIO"
}
如何替换此值?
这是一条线: global_informations["quantite_unit_fonct"] = type_fdes_dictionary[global_informations["quantite_unit_fonct"]]
global_informations = {"id": "ID_PRODUIT",
"name": "NOM_PRODUIT",
"type_fdes": 1,
"nb_refs_commerciales": "NB_REF_COMM",
"quantite_unit_fonct": "QUANTITE_UF",
"type_unit_fonct": "ID_UNIT_UF",
"duree_vie": "DVT",
"carbon_biogenique": "CARBONE_BIO"
}
type_fdes_dictionary = {1: "individuel",
2: "collectif",
3: "defaut"
}
print({k: type_fdes_dictionary.get(v, v) for k, v in global_informations.items()})
output:{'id':'ID_PRODUIT','name':'NOM_PRODUIT', 'type_fdes':'individuel' ,'nb_refs_commerciales':'NB_REF_COMM','quantite_unit_font':'QUANTITE_Tunit':'ID_type ,'duree_vie':'DVT','carbon_biogenique':'CARBONE_BIO'}
有几种方法可以做到这一点 -
for key,value in global_informations.items():
if key=='type_fdes':
global_informations[key] = type_fdes_dictionary[value]
global_informations['type_fdes'] = type_fdes_dictionary[global_informations['type_fdes']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.