Solution Exercice 54: concaténation des dictionnaires Python

Solution exercice 54 comment concatenation des dictionnaires en python via la methode update

Exercice 54

On considère les trois dictionnaires Pythons qui regroupe la totalité du matériels informatiques:

dicPC={"HP": 11 , "Acer": 7 , "Lenovo": 17 , "Del": 23}
dicPhone={"Sumsung": 22 , "Iphone": 9 , "Other": 13 }
dicTablette = {"Sumsung": 15 , "Other": 13}

Écrire un programme Python qui regroupe en concaténant ces trois dictionnaires en un seule avec deux méthodes différentes.

Solution

1 ère méthode




# coding: utf-8
dicPC={"HP": 11 , "Acer": 7 , "Lenovo": 17 , "Del": 23}
dicPhone={"Sumsung": 22 , "Iphone": 9 , "Other": 13 }
dicTablette = {"Sumsung": 15 , "Other": 13}

# on crée un dictionnaire vide qui va contenir les autres dictionnaires
dicTotal = {}

# on ajoute les dictionnaire un par un via la méthode update
dicTotal.update(dicPC)
dicTotal.update(dicPhone)
dicTotal.update(dicTablette)
print(dicTotal)

Ce qui affiche après exécution:

{'HP': 11, 'Acer': 7, 'Lenovo': 17, 'Del': 23, 'Sumsung': 15, 'Iphone': 9, 'Other': 13}

Solution

2ème méthode



# coding: utf-8
dicPC={"HP": 11 , "Acer": 7 , "Lenovo": 17 , "Del": 23}
dicPhone={"Sumsung": 22 , "Iphone": 9 , "Other": 13 }
dicTablette = {"Sumsung": 15 , "Other": 13}
# on crée un dictionnaire qui va contenir les autres 
dicTotal = {}
# on ajoute les dictionnaires via la boucle for
for d in [dicPC , dicTablette, dicPhone]:
    dicTotal.update(d)

print(dicTotal)

Younes Derfoufi
CRMEF OUJDA

3 thoughts on “Solution Exercice 54: concaténation des dictionnaires Python

Leave a Reply to UNCKNOW Cancel reply

Your email address will not be published. Required fields are marked *