Λεξικό Python (με παραδείγματα)

Σε αυτό το σεμινάριο, θα μάθετε τα πάντα για τα λεξικά Python. πώς δημιουργούνται, πρόσβαση, προσθήκη, αφαίρεση στοιχείων από αυτά και διάφορες ενσωματωμένες μεθόδους.

Βίντεο: Λεξικά Python για αποθήκευση ζεύγους κλειδιού / τιμής

Το λεξικό Python είναι μια μη ταξινομημένη συλλογή αντικειμένων. Κάθε στοιχείο ενός λεξικού έχει ένα key/valueζεύγος.

Τα λεξικά βελτιστοποιούνται για να ανακτούν τιμές όταν το κλειδί είναι γνωστό.

Δημιουργία λεξικού Python

Η δημιουργία ενός λεξικού είναι τόσο απλή όσο η τοποθέτηση αντικειμένων μέσα σε σγουρά αγκύλες που ()διαχωρίζονται με κόμματα.

Ένα στοιχείο έχει ένα keyκαι ένα αντίστοιχο valueπου εκφράζεται ως ζεύγος ( κλειδί: τιμή ).

Ενώ οι τιμές μπορούν να είναι οποιουδήποτε τύπου δεδομένων και μπορούν να επαναληφθούν, τα κλειδιά πρέπει να είναι αμετάβλητου τύπου (συμβολοσειρά, αριθμός ή πλειάδα με αμετάβλητα στοιχεία) και πρέπει να είναι μοναδικά.

 # empty dictionary my_dict = () # dictionary with integer keys my_dict = (1: 'apple', 2: 'ball') # dictionary with mixed keys my_dict = ('name': 'John', 1: (2, 4, 3)) # using dict() my_dict = dict((1:'apple', 2:'ball')) # from sequence having each item as a pair my_dict = dict(((1,'apple'), (2,'ball')))

Όπως μπορείτε να δείτε από ψηλά, μπορούμε επίσης να δημιουργήσουμε ένα λεξικό χρησιμοποιώντας την ενσωματωμένη dict()λειτουργία.

Πρόσβαση σε στοιχεία από το λεξικό

Ενώ η ευρετηρίαση χρησιμοποιείται με άλλους τύπους δεδομένων για πρόσβαση σε τιμές, ένα λεξικό χρησιμοποιεί keys. Τα κλειδιά μπορούν να χρησιμοποιηθούν είτε μέσα σε αγκύλες ()είτε με τη get()μέθοδο.

Εάν χρησιμοποιούμε τις αγκύλες (), KeyErrorανυψώνεται σε περίπτωση που δεν βρεθεί κλειδί στο λεξικό. Από την άλλη πλευρά, η get()μέθοδος επιστρέφει Noneεάν το κλειδί δεν βρεθεί.

 # get vs () for retrieving elements my_dict = ('name': 'Jack', 'age': 26) # Output: Jack print(my_dict('name')) # Output: 26 print(my_dict.get('age')) # Trying to access keys which doesn't exist throws error # Output None print(my_dict.get('address')) # KeyError print(my_dict('address'))

Παραγωγή

 Jack 26 None Traceback (τελευταία πρόσφατη κλήση): Αρχείο ", γραμμή 15, σε έντυπη μορφή (my_dict ('address')) KeyError: 'address'

Αλλαγή και προσθήκη στοιχείων λεξικού

Τα λεξικά είναι μεταβλητά. Μπορούμε να προσθέσουμε νέα στοιχεία ή να αλλάξουμε την αξία των υπαρχόντων αντικειμένων χρησιμοποιώντας έναν χειριστή ανάθεσης.

Εάν το κλειδί υπάρχει ήδη, τότε η υπάρχουσα τιμή ενημερώνεται. Σε περίπτωση που το κλειδί δεν υπάρχει, προστίθεται ένα νέο ζεύγος ( κλειδί: τιμή ) στο λεξικό.

 # Changing and adding Dictionary Elements my_dict = ('name': 'Jack', 'age': 26) # update value my_dict('age') = 27 #Output: ('age': 27, 'name': 'Jack') print(my_dict) # add item my_dict('address') = 'Downtown' # Output: ('address': 'Downtown', 'age': 27, 'name': 'Jack') print(my_dict)

Παραγωγή

 ('όνομα': 'Τζακ', 'ηλικία': 27) ('όνομα': 'Τζακ', 'ηλικία': 27, 'διεύθυνση': 'Downtown')

Κατάργηση στοιχείων από το Λεξικό

Μπορούμε να καταργήσουμε ένα συγκεκριμένο αντικείμενο σε ένα λεξικό χρησιμοποιώντας τη pop()μέθοδο. Αυτή η μέθοδος καταργεί ένα στοιχείο με τα παρεχόμενα keyκαι επιστρέφει το value.

Η popitem()μέθοδος μπορεί να χρησιμοποιηθεί για την αφαίρεση και επιστροφή ενός αυθαίρετου (key, value)ζεύγους στοιχείων από το λεξικό. Όλα τα αντικείμενα μπορούν να αφαιρεθούν ταυτόχρονα, χρησιμοποιώντας τη clear()μέθοδο.

Μπορούμε επίσης να χρησιμοποιήσουμε τη delλέξη-κλειδί για να αφαιρέσουμε μεμονωμένα στοιχεία ή ολόκληρο το λεξικό.

 # Removing elements from a dictionary # create a dictionary squares = (1: 1, 2: 4, 3: 9, 4: 16, 5: 25) # remove a particular item, returns its value # Output: 16 print(squares.pop(4)) # Output: (1: 1, 2: 4, 3: 9, 5: 25) print(squares) # remove an arbitrary item, return (key,value) # Output: (5, 25) print(squares.popitem()) # Output: (1: 1, 2: 4, 3: 9) print(squares) # remove all items squares.clear() # Output: () print(squares) # delete the dictionary itself del squares # Throws Error print(squares)

Παραγωγή

 16 (1: 1, 2: 4, 3: 9, 5: 25) (5, 25) (1: 1, 2: 4, 3: 9) () Traceback (τελευταία τελευταία κλήση): Αρχείο "", γραμμή 30, σε έντυπη μορφή (τετράγωνα) NameError: το όνομα «τετράγωνα» δεν έχει οριστεί

Μέθοδοι λεξικού Python

Οι μέθοδοι που είναι διαθέσιμες με ένα λεξικό παρουσιάζονται παρακάτω. Μερικά από αυτά έχουν ήδη χρησιμοποιηθεί στα παραπάνω παραδείγματα.

Μέθοδος Περιγραφή
Σαφή() Καταργεί όλα τα στοιχεία από το λεξικό.
αντίγραφο() Επιστρέφει ένα ρηχό αντίγραφο του λεξικού.
από τα πλήκτρα (seq (, v)) Returns a new dictionary with keys from seq and value equal to v (defaults to None).
get(key(,d)) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new object of the dictionary's items in (key, value) format.
keys() Returns a new object of the dictionary's keys.
pop(key(,d)) Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError.
popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty.
setdefault(key(,d)) Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None).
update((other)) Updates the dictionary with the key/value pairs from other, overwriting existing keys.
values() Returns a new object of the dictionary's values

Here are a few example use cases of these methods.

 # Dictionary Methods marks = ().fromkeys(('Math', 'English', 'Science'), 0) # Output: ('English': 0, 'Math': 0, 'Science': 0) print(marks) for item in marks.items(): print(item) # Output: ('English', 'Math', 'Science') print(list(sorted(marks.keys())))

Output

 ('Math': 0, 'English': 0, 'Science': 0) ('Math', 0) ('English', 0) ('Science', 0) ('English', 'Math', 'Science')

Python Dictionary Comprehension

Dictionary comprehension is an elegant and concise way to create a new dictionary from an iterable in Python.

Dictionary comprehension consists of an expression pair (key: value) followed by a for statement inside curly braces ().

Here is an example to make a dictionary with each item being a pair of a number and its square.

 # Dictionary Comprehension squares = (x: x*x for x in range(6)) print(squares)

Output

 (0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25)

This code is equivalent to

 squares = () for x in range(6): squares(x) = x*x print(squares)

Output

 (0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25)

A dictionary comprehension can optionally contain more for or if statements.

An optional if statement can filter out items to form the new dictionary.

Here are some examples to make a dictionary with only odd items.

 # Dictionary Comprehension with if conditional odd_squares = (x: x*x for x in range(11) if x % 2 == 1) print(odd_squares)

Output

 (1: 1, 3: 9, 5: 25, 7: 49, 9: 81)

To learn more dictionary comprehensions, visit Python Dictionary Comprehension.

Other Dictionary Operations

Dictionary Membership Test

We can test if a key is in a dictionary or not using the keyword in. Notice that the membership test is only for the keys and not for the values.

 # Membership Test for Dictionary Keys squares = (1: 1, 3: 9, 5: 25, 7: 49, 9: 81) # Output: True print(1 in squares) # Output: True print(2 not in squares) # membership tests for key only not value # Output: False print(49 in squares)

Output

 True True False

Iterating Through a Dictionary

We can iterate through each key in a dictionary using a for loop.

 # Iterating through a Dictionary squares = (1: 1, 3: 9, 5: 25, 7: 49, 9: 81) for i in squares: print(squares(i))

Output

 1 9 25 49 81

Dictionary Built-in Functions

Ενσωματωμένες λειτουργίες αρέσει all(), any(), len(), cmp(), sorted(), κλπ χρησιμοποιούνται συνήθως με λεξικά να εκτελέσει διάφορες εργασίες.

Λειτουργία Περιγραφή
όλα() Επιστρέψτε Trueεάν όλα τα πλήκτρα του λεξικού είναι αληθή (ή εάν το λεξικό είναι κενό).
όποιος() Επιστρέψτε Trueεάν ισχύει κάποιο κλειδί του λεξικού. Εάν το λεξικό είναι κενό, επιστρέψτε False.
Λέν () Επιστρέψτε το μήκος (ο αριθμός των αντικειμένων) στο λεξικό.
cmp () Συγκρίνει στοιχεία δύο λεξικών. (Μη διαθέσιμο στο Python 3)
ταξινομημένο () Επιστρέψτε μια νέα ταξινομημένη λίστα κλειδιών στο λεξικό.

Ακολουθούν ορισμένα παραδείγματα που χρησιμοποιούν ενσωματωμένες συναρτήσεις για να λειτουργήσουν με ένα λεξικό.

 # Dictionary Built-in Functions squares = (0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81) # Output: False print(all(squares)) # Output: True print(any(squares)) # Output: 6 print(len(squares)) # Output: (0, 1, 3, 5, 7, 9) print(sorted(squares))

Παραγωγή

 False True 6 (0, 1, 3, 5, 7, 9)

ενδιαφέροντα άρθρα...