<?xml version="1.0"?>
<rss version="2.0">
   <channel>
      <title>Collections Python by Imane Bourous</title>
      <link>https://padlet.com/imanebourous/2b3c5z1ck7gy6qsk</link>
      <description>Définitions et exemples </description>
      <language>en-us</language>
      <pubDate>2025-06-20 07:56:51 UTC</pubDate>
      <lastBuildDate>2025-06-23 13:08:44 UTC</lastBuildDate>
      <webMaster>hello@padlet.com</webMaster>
      <image>
         <url></url>
      </image>
      <item>
         <title>ismail</title>
         <author></author>
         <link>https://padlet.com/imanebourous/2b3c5z1ck7gy6qsk/wish/3497033957</link>
         <description><![CDATA[<p><strong><mark>DefautlDict</mark> </strong>: version developpee/amelioree de dict qui evite erreurs quand il n'y a pas existance d'un cle  </p><p><strong>Exemple :</strong></p><p>from collections import DefaultDict</p><p>d = defaultdict(list) </p><p>d['Key1].append('val1')</p><p> print(d['Key1'])   </p><p> print(d['thingNotInDict']) </p><p><strong>Exemple :</strong></p><p>from collections import defaultdict</p><p>di = defaultdict(lambda: "unknown")</p><p>di['nom'] = 'Ismail'</p><p>print(di['nom'])     # Ismail</p><p>print(d['prenom'])   # unknown</p><p><br></p><p>                                                                             ************                             <strong><mark>ChainMap</mark></strong> : <strong>cree une chaine de dictionnaires</strong>. Quand tu cherches une cle, il donne prioritee ou premier dictionnaire ou il passe ou deuxieme dictionnaire si le cle n'existe pas dans premier dictionnaire et ainsi de suite       </p><p><strong>Exemple :</strong></p><p>from collections import ChainMap </p><p>di1 = {'Nom': "Wick", 'Prenom': "John"} </p><p>di2 = {'bornIn': 1994, 'age': 32}</p><p>TwoDi = ChainMap(di1, di2) </p><p>print(TwoDi['Nom']) # return Wick la valeur du Nom</p><p>                                                                          ************                <strong><mark>OrderedDict</mark></strong><mark> </mark>: une version organisee pour conservee l'ordre d'insertion</p><p><strong>Exemple : </strong></p><p>from collections import OrderedDict</p><p>di = OrderedDict()</p><p>di['a'] = "pomme"</p><p>di['b'] = "bonbon"</p><p>di['c'] = 3</p><p>print(di) </p><p>#Output:{a:"pomme", b:"bonbon", c:3}</p><p><br></p><p>} </p><p><br></p>]]></description>
         <enclosure url="" />
         <pubDate>2025-06-20 08:06:53 UTC</pubDate>
         <guid>https://padlet.com/imanebourous/2b3c5z1ck7gy6qsk/wish/3497033957</guid>
      </item>
      <item>
         <title>hanane</title>
         <author></author>
         <link>https://padlet.com/imanebourous/2b3c5z1ck7gy6qsk/wish/3497039143</link>
         <description><![CDATA[<p><strong>ChainMap</strong>: c’est un outil en Python qui permet de regrouper plusieurs dictionnaires pour chercher les clés comme s’ils étaient un seul dictionnaire</p><ol><li><p><em> syntaxe:</em></p></li></ol><p> from collections import ChainMap </p><p>cm = ChainMap(dict1, dict2, dict3, ...) </p><p>----<em>exemple1 </em> ----</p><p>from collections import ChainMap </p><p>d1={'a':1,'b':2} d2={'c':3,'d':4} d3= {'e':5,'f':6} </p><p>#Définitiond’une ChainMap -------- </p><p>c= ChainMap(d1,d2, d3) </p><p>print(c) </p><p>#ChainMap({'a':1,'b': 2}, {'c':3,'d':4}, {'e':5,'f': 6}) </p><p>-------<em>exemple 2</em>:--------</p><p> from collections import ChainMap</p><p> d1 = {'a': 1, '<strong>b': 2</strong>} </p><p>d2 = {'c': 3, 'd': 4} </p><p>d3 = {'e': 5, '<strong>b': 6</strong>} </p><p># Définition d’une ChainMap</p><p> c = ChainMap(d1, d2, d3) </p><p>print(c) </p><p># ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'b': 6}) </p><p>for k, v in c.items():</p><p> #parcourir les éléments de c print(k, v,end= ‘ , ‘)</p><p> # Résulat : e 5, <strong>b 2</strong>, c 3, d 4, a 1</p>]]></description>
         <enclosure url="" />
         <pubDate>2025-06-20 08:14:00 UTC</pubDate>
         <guid>https://padlet.com/imanebourous/2b3c5z1ck7gy6qsk/wish/3497039143</guid>
      </item>
      <item>
         <title>hanane </title>
         <author></author>
         <link>https://padlet.com/imanebourous/2b3c5z1ck7gy6qsk/wish/3497053853</link>
         <description><![CDATA[<p><strong><mark>La collection Counter</mark>:</strong></p><p><strong>Counter est une classe spéciale</strong> qui sert à <strong>compter combien de fois chaque élément apparaît</strong> dans une liste, un texte, etc.</p><p> -----syntaxe-----</p><p><strong>from</strong> collections <strong>import</strong> Counter</p><p>compte = Counter(itérable)</p><p><br></p><p><mark>itérable</mark>: peut être : une liste, une chaîne, un tuple, etc.</p><p><mark>Counter</mark> retourne un dictionnaire spécial qui compte les éléments</p><p>-----exemple ---</p><pre><code>from collections import Counter
c = Counter() 
# compteur vide
print(c)  #affiche Counter()
c = Counter('gallahad') #compteur avec un iterable
print(c) 
#affiche Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})
c = Counter({'red': 4, 'blue': 2}) 
# un compteur avec un mapping
print(c)
 #affcihe: Counter({'red': 4, 'blue': 2})
c = Counter(cats=4, dogs=8)
#un compteur avec key=valeur
print(c)
 #affiche: Counter({'dogs': 8, 'cats': 4})</code></pre><p><strong> remarque:</strong></p><p>Si on demande une valeur n’étant pas dans notre liste il retourne 0 et non pas KeyError</p><p><strong>Méthodes intéressantes&nbsp;</strong></p><ul><li><p><strong>elements</strong> () :&nbsp; retourne une liste de tous les éléments du compteur.</p><p>exemple:</p><pre><code>from collections import Counter
c = Counter(a=4, b=2, c=0, d=-2)
sorted(c.elements()) 
#affiche ['a', 'a', 'a', 'a', 'b', 'b']</code></pre></li><li><p>    <strong>most_common([n])</strong> :retourne les n éléments les plus présents dans le compteur</p><pre><code>from collections import Counter
c = Counter(a=4, b=2, c=0, d=-2)
print(Counter('abracadabra').most_common(3))
#affiche [('a', 5), ('b', 2), ('r', 2)]</code></pre></li><li><p><strong>substract([iterable or mapping]) : </strong>permet de soustraire des éléments </p><p>d’un compteur.&nbsp;</p><p>-----exemple-----</p><pre><code>from collections import Counter
c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
print(c.subtract(d)) 
#affcihe Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})</code></pre></li></ul><p><br></p>]]></description>
         <enclosure url="" />
         <pubDate>2025-06-20 08:31:04 UTC</pubDate>
         <guid>https://padlet.com/imanebourous/2b3c5z1ck7gy6qsk/wish/3497053853</guid>
      </item>
      <item>
         <title>hanane</title>
         <author></author>
         <link>https://padlet.com/imanebourous/2b3c5z1ck7gy6qsk/wish/3497062624</link>
         <description><![CDATA[<p><strong><mark>La collection OrdredDict:</mark></strong></p><p>Les collections.OrderedDict sont comme les dict. mais ils se rappellent l’ordre d’entrée des valeurs. Si on itère dessus les données seront retournées dans l’ordre d’ajout dans notre dict.</p><p>-----syntaxe----</p><p><strong>from</strong> collections <strong>import</strong> OrderedDict</p><p># Création d’un OrderedDict</p><p>mon_dict = OrderedDict()</p><p>mon_dict['a'] = 1</p><p>mon_dict['b'] = 2</p><p>mon_dict['c'] = 3</p><p>print(mon_dict)</p><p><br></p><p><strong><em> ---Méthodes intéressantes---</em></strong></p><ul><li><p><strong>popitem(last=True) :&nbsp; </strong>fait sortir une paire clé-valeur de notre dictionnaire et si l’argument last est a ‘True’ alors les pairs seront retournées en LIFO sinon ce sera en FIFO</p></li><li><p><strong>move_to_end(key, last=True) : </strong>permet de déplacer une clé à la fin de notre dictionnaire si last est à True sinon au début de notre dict.</p><pre><code>from collections import OrderedDict
d=OrderedDict()
d['a']=‘1’ #remplir d
d['b']='2'
d['c']='3'
d['d']='4’
d.move_to_end('b’)
print(d) 
#affiche OrderedDict([('a', '1'), ('c', '3'), ('d', '4'), ('b', '2')])
d.move_to_end('b',last=False)
print(d) #affiche OrderedDict([('b', '2'), ('a', '1'), ('c', '3'), ('d', '4')])
print(d.popitem(True)) #affiche('d', '4')
print(d) #affiche OrderedDict([('b', '2'), ('a', '1'), ('c', '3')])</code></pre></li></ul><p><br></p><p><br></p><p><br></p>]]></description>
         <enclosure url="" />
         <pubDate>2025-06-20 08:43:18 UTC</pubDate>
         <guid>https://padlet.com/imanebourous/2b3c5z1ck7gy6qsk/wish/3497062624</guid>
      </item>
      <item>
         <title>Mohamed Aymane Chakouri </title>
         <author></author>
         <link>https://padlet.com/imanebourous/2b3c5z1ck7gy6qsk/wish/3497081510</link>
         <description><![CDATA[<p><strong><em><mark>1. ChainMap</mark></em></strong></p><p>   Définition:  </p><p>Regroupe plusieurs dictionnaires en une seule vue. Les recherches sont effectuées successivement dans chaque dictionnaire jusqu'à trouver la clé. Idéal pour gérer des configurations hiérarchiques.</p><p>Exemple:</p><p>python</p><p>from collections import ChainMap</p><p>d1 = {'a': 1, 'b': 2}</p><p>d2 = {'b': 3, 'c': 4}</p><p>chain = ChainMap(d1, d2)</p><p>print(chain['a'])  # Output: 1 (trouvé dans d1)</p><p>print(chain['b'])  # Output: 2 (première occurrence dans d1)</p><p>print(chain['c'])  # Output: 4 (trouvé dans d2)</p><p><br></p><p><br></p><p>     <strong><em><mark>2. Counter</mark></em></strong></p><p><strong>Définition</strong> :  </p><p>Compte automatiquement les occurrences d'éléments dans un itérable (listes, chaînes, etc.). Les éléments deviennent des clés et leurs compteurs des valeurs.</p><p><strong>Exemple</strong> :</p><p>   python</p><p>from collections import Counter</p><p>liste = ['a', 'b', 'a', 'c', 'b', 'a']</p><p>compteur = Counter(liste)</p><p>print(compteur)          # Output: Counter({'a': 3, 'b': 2, 'c': 1})</p><p>print(compteur.most_common(1))  # Output: [('a', 3)] (élément le plus fréquent)</p><p><br></p><p><br></p><p><br></p><p><br></p><p>      <strong><em><mark>3. defaultdict  </mark></em></strong></p><p><strong>Définition</strong> :  </p><p>Un dictionnaire qui retourne une valeur par défaut si une clé est absente, évitant les erreurs `KeyError`. La valeur par défaut est définie par une fonction (ex: `int`, `list`).</p><p><strong>Exemple</strong> :</p><p>    python</p><p>from collections import defaultdict</p><p>dd = defaultdict(list)  # Valeur par défaut: liste vide</p><p>dd['clé1'].append(1)    # Pas besoin d'initialiser la clé</p><p>print(dd['clé1'])  # Output: [1]</p><p>print(dd['clé2'])  # Output: [] (clé absente → retourne une liste vide)</p><p><br></p><p><br></p><p><br></p><p>      <strong><em><mark>4. OrderedDict </mark></em></strong></p><p><strong>Définition</strong> :  </p><p>Maintient l'ordre d'insertion des clés (utile avant Python 3.7 où les `dict` standards ne le garantissaient pas). Offre des méthodes spécifiques comme `move_to_end()`.</p><p><strong>Exemple</strong> :</p><p>```python</p><p>from collections import OrderedDict</p><p>od = OrderedDict()</p><p>od['z'] = 1</p><p>od['a'] = 2</p><p>od['c'] = 3</p><p>print(list(od.keys()))  # Output: ['z', 'a', 'c'] (ordre d'insertion conservé)</p><p>od.move_to_end('z')    # Déplace 'z' à la fin</p><p>print(list(od.keys()))  # Output: ['a', 'c', 'z']</p>]]></description>
         <enclosure url="" />
         <pubDate>2025-06-20 09:11:41 UTC</pubDate>
         <guid>https://padlet.com/imanebourous/2b3c5z1ck7gy6qsk/wish/3497081510</guid>
      </item>
      <item>
         <title>hanane</title>
         <author></author>
         <link>https://padlet.com/imanebourous/2b3c5z1ck7gy6qsk/wish/3497083708</link>
         <description><![CDATA[<p><strong><mark>La collection defaultDict :</mark></strong></p><p>defaultdict du module de collections permet de rassembler les informations dans les dictionnaires de manière rapide et concise. defaultdict se comporte différemment d’un dictionnaire ordinaire. Au lieu de soulever une KeyError sur une clé manquante, defaultdict appelle la valeur de remplacement sans argument pour créer un nouvel objet</p><p>-----exemple :-------</p><pre><code>from Collections import defaultdict
my_defaultdict =defaultdict(list)
print(my_defaultdict["missing"]) #affcihe []</code></pre><p><br></p><p><strong>Autres types de valeurs par défaut </strong>:</p><p>int : 0</p><p> float 0.0</p><p> str  : ' '</p><p> list [ ]</p><p> set :set()</p><p> dict :{ }</p><p> -----exemple2-----</p><pre><code>from collections import defaultdict
def default_message():
 return "key is not there"
defaultdcit_obj= defaultdict(default_message)
defaultdcit_obj["key1"]="value1"
defaultdcit_obj["key2"]="value2"
print(defaultdcit_obj["key1"]) #affiche: value1
print(defaultdcit_obj["key2"]) #affiche: value2
print(defaultdcit_obj["key3"]) #affiche: key is not there</code></pre><p>  -----exemple3 -----</p><p>Lorsque la classe int est fournie comme fonction par défaut, la valeur par défaut retournée est zéro.</p><pre><code>from collections import defaultdict
defaultdcit_obj =defaultdict(int)
defaultdcit_obj["key1"]="value1"
defaultdcit_obj["key2"]="value2"
print(defaultdcit_obj["key1"]) #affiche: value1
print(defaultdcit_obj["key2"]) #affiche: value2
print(defaultdcit_obj["key3"]) #affiche: 0</code></pre><p> <strong> exercice  :</strong></p><ul><li><p>Écrire un programme Python qui <strong>compte combien de fois chaque mot apparaît</strong> dans une phrase donnée, en utilisant defaultdict(int)</p></li><li><p>phrase = "chat chien chat oiseau chien chat"</p></li></ul><p>Exemple attendu à la fin:</p><p>{</p><p>  'chat': 3,</p><p>  'chien': 2,</p><p>  'oiseau': 1</p><p>}</p><p><br></p><p><br></p><p><br></p>]]></description>
         <enclosure url="" />
         <pubDate>2025-06-20 09:15:21 UTC</pubDate>
         <guid>https://padlet.com/imanebourous/2b3c5z1ck7gy6qsk/wish/3497083708</guid>
      </item>
   </channel>
</rss>
