Python >> Tutoriel Python >  >> Python

Python OrderedDict

OrderedDict est une sous-classe du dictionnaire, qui maintient l'ordre dans lequel les éléments/éléments y sont ajoutés.

OrderedDict préserve l'ordre d'insertion des éléments. Un dict par défaut n'enregistre pas la commande et aboutit à l'itération dans un ordre arbitraire.

Initialement, nous devons importer le module de collections pour utiliser le module de bibliothèque OrderedDict. Nous pouvons également importer uniquement la classe OrderedDict à partir du module de collections.

import collections

from collections import OrderedDict

Fonctionnalités Python OrderedDict

  • Création d'un objet OrderedDict
  • Ajout d'éléments à OrderedDict
  • Remplacement des éléments de OrderedDict
  • Suppression d'éléments de OrderedDict
  • Modification de la valeur-clé
  • Fonction move_to_end()
  • Élément pop OrderedDict
  • Itération inverse
  • Test d'égalité OrderedDict

1. Création de l'objet OrderedDict

Le OrderedDict() fonction est utilisée pour la création de l'objet.

from collections import OrderedDict


my_input = {'Pune': 'Maharashtra', 'Ahemadnagar': 'Gujarat', 'Orrisa': 'Bhubhaneshwar'}

# creating ordered dict from dict
ordered_input = OrderedDict(my_input)
print(ordered_input)

Sortie :

OrderedDict([('Pune', 'Maharashtra'), ('Ahemadnagar', 'Gujarat'), ('Orrisa', 'Bhubhaneshwar')])

2. Ajout d'éléments à OrderedDict

from collections import OrderedDict


my_input = {'Pune': 'Maharashtra', 'Ahemadnagar': 'Gujarat', 'Orrisa': 'Bhubhaneshwar'}

# creating ordered dict from dict
ordered_input = OrderedDict(my_input)
#print(ordered_input)

print("Adding item to OrderedDict....")
ordered_input['Hyderabad'] = 'Karnataka'
print(ordered_input)

Sortie :

Adding item to OrderedDict....
OrderedDict([('Pune', 'Maharashtra'), ('Ahemadnagar', 'Gujarat'), ('Orrisa', 'Bhubhaneshwar'), ('Hyderabad', 'Karnataka')])

3. Remplacement des éléments de OrderedDict

from collections import OrderedDict


my_input = {'Pune': 'Maharashtra', 'Ahemadnagar': 'Gujarat', 'Orrisa': 'Bhubhaneshwar'}

# creating ordered dict from dict
ordered_input = OrderedDict(my_input)
#print(ordered_input)

print("Replacing item from OrderedDict....")
ordered_input['Pune'] = 'Satara'
print(ordered_input)

Sortie :

Adding items to OrderedDict....
OrderedDict([('Pune', 'Satara'), ('Ahemadnagar', 'Gujarat'), ('Orrisa', 'Bhubhaneshwar')])

4. Suppression d'éléments de OrderedDict

from collections import OrderedDict


my_input = {'Pune': 'Maharashtra', 'Ahemadnagar': 'Gujarat', 'Orrisa': 'Bhubhaneshwar'}

# creating ordered dict from dict
ordered_input = OrderedDict(my_input)
#print(ordered_input)

print('Removal of item from OrderedDict....')
ordered_input.pop('Pune')
print(ordered_input)

Sortie :

Removal of item from OrderedDict....
OrderedDict([('Ahemadnagar', 'Gujarat'), ('Orrisa', 'Bhubhaneshwar')])

5. Changement de clé-valeur dans un OrderedDict

Dans un OrderedDict, si la valeur correspondant à une clé particulière est modifiée, la position/l'index de cette clé reste inchangé.

from collections import OrderedDict


my_input = {'Pune': 'Maharashtra', 'Ahemadnagar': 'Gujarat', 'Orrisa': 'Bhubhaneshwar'}

# creating ordered dict from dict
print('Before the change.....')
ordered_input = OrderedDict(my_input)
print(ordered_input)

print('After the change.....')
ordered_input['Pune'] = 'Kiara'
print(ordered_input)

Sortie :

Before the change.....
OrderedDict([('Pune', 'Maharashtra'), ('Ahemadnagar', 'Gujarat'), ('Orrisa', 'Bhubhaneshwar')])
After the change.....
OrderedDict([('Pune', 'Kiara'), ('Ahemadnagar', 'Gujarat'), ('Orrisa', 'Bhubhaneshwar')])

6. fonction move_to_end()

Le move_to_end() déplace une paire clé-valeur particulière à la fin du dict.

from collections import OrderedDict


my_input = {'Pune': 'Maharashtra', 'Ahemadnagar': 'Gujarat', 'Orrisa': 'Bhubhaneshwar'}

# creating ordered dict from dict
print('Before using the move_to_end().....')
ordered_input = OrderedDict(my_input)
print(ordered_input)

print('After using the move_to_end().....')
ordered_input.move_to_end('Pune')
print(ordered_input)

Sortie :

Before using the move_to_end().....
OrderedDict([('Pune', 'Maharashtra'), ('Ahemadnagar', 'Gujarat'), ('Orrisa', 'Bhubhaneshwar')])
After using the move_to_end().....
OrderedDict([('Ahemadnagar', 'Gujarat'), ('Orrisa', 'Bhubhaneshwar'), ('Pune', 'Maharashtra')])

7. Élément pop OrderedDict

Cette fonction apparaît et renvoie le dernier élément en sortie.

from collections import OrderedDict


my_input = {'Pune': 'Maharashtra', 'Ahemadnagar': 'Gujarat', 'Orrisa': 'Bhubhaneshwar'}

# creating ordered dict from dict
print('Original input dict.....')
ordered_input = OrderedDict(my_input)
print(ordered_input)


result = ordered_input.popitem(True)
print('The popped item is: ')
print(result)

print(ordered_input)

Sortie :

Original input dict.....
OrderedDict([('Pune', 'Maharashtra'), ('Ahemadnagar', 'Gujarat'), ('Orrisa', 'Bhubhaneshwar')])
The popped item is: 
('Orrisa', 'Bhubhaneshwar')
OrderedDict([('Pune', 'Maharashtra'), ('Ahemadnagar', 'Gujarat')])

8. Itération inverse

from collections import OrderedDict


my_input = {'Pune': 'Maharashtra', 'Ahemadnagar': 'Gujarat', 'Orrisa': 'Bhubhaneshwar'}

# creating ordered dict from dict
print('Original input dict.....')
ordered_input = OrderedDict(my_input)
print(ordered_input)

print('Reversed OrderedDict.....')

for elements in reversed(ordered_input):
    print(elements)

Sortie :

Original input dict.....
OrderedDict([('Pune', 'Maharashtra'), ('Ahemadnagar', 'Gujarat'), ('Orrisa', 'Bhubhaneshwar')])
Reversed OrderedDict.....
Orrisa
Ahemadnagar
Pune

9. Test d'égalité OrderedDict

from collections import OrderedDict

# creating regular dict..
my_input1 = {1:'one' , 2:'two'}
my_input2 = {2:'two' , 1:'one'}

#creating ordereddict..
ordered_input1 = OrderedDict({1:'one' , 2:'two'})
ordered_input2 = OrderedDict({2:'two' , 1:'one'})

print(my_input1 == ordered_input1)
print(my_input1 == my_input2)
print(ordered_input1 == ordered_input2)

Sortie :

True
True
False

Conclusion

Ainsi, dans cet article, nous avons compris la différence entre Dictionary standard et OrderedDict et avons jeté un œil aux fonctionnalités offertes par OrderedDict.


Références

  • Python OrderedDict
  • Documentation OrderedDict

Post précédent