Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!
Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount
Λεξικά
A dictionary είναι ένας τύπος δεδομένων παρόμοιος με τους πίνακες, αλλά λειτουργεί με κλειδιά και τιμές αντί με δείκτες. Κάθε τιμή αποθηκευμένη σε ένα dictionary μπορεί να προσπελαστεί χρησιμοποιώντας ένα κλειδί, το οποίο μπορεί να είναι οποιοδήποτε τύπος αντικειμένου (μια συμβολοσειρά, ένας αριθμός, μια λίστα, κτλ.) αντί να χρησιμοποιούμε το δείκτη του για την πρόσβαση.
Για παράδειγμα, μια βάση δεδομένων τηλεφωνικών αριθμών θα μπορούσε να αποθηκευτεί χρησιμοποιώντας ένα dictionary όπως αυτό:
Εναλλακτικά, ένα dictionary μπορεί να αρχικοποιηθεί με τις ίδιες τιμές χρησιμοποιώντας την παρακάτω σημειογραφία:
Iterating over dictionaries
Τα dictionaries μπορούν να περαστούν σε επανάληψη, ακριβώς όπως μια λίστα. Ωστόσο, σε αντίθεση με μια λίστα, ένα dictionary δεν διατηρεί τη σειρά των αποθηκευμένων τιμών. Για να επαναλάβετε τα ζεύγη κλειδιού-τιμής, χρησιμοποιήστε την παρακάτω σύνταξη:
Removing a value
Για να αφαιρέσετε ένα καθορισμένο δείκτη, χρησιμοποιήστε μία από τις παρακάτω σημειογραφίες:
ή:
Exercise
Προσθέστε τον "Jake" στο phonebook με τον τηλεφωνικό αριθμό 938273443, και αφαιρέστε την Jill από το phonebook.
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
# your code goes here
# testing code
if "Jake" in phonebook:
print("Jake is listed in the phonebook.")
if "Jill" not in phonebook:
print("Jill is not listed in the phonebook.")
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
# your code goes here
phonebook["Jake"] = 938273443
del phonebook["Jill"]
# testing code
if "Jake" in phonebook:
print("Jake is listed in the phonebook.")
if "Jill" not in phonebook:
print("Jill is not listed in the phonebook.")
test_output_contains("Jake is listed in the phonebook.")
test_output_contains("Jill is not listed in the phonebook.")
success_msg("Nice work!")
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!