Cheatography
https://cheatography.com
DictionaryA dictionary is changeable and indexed like a list and unordred like a set. A dictionairy contains keys and values. |
Dictionary exampleCar = { "brand": "Ford", "model": "Focus", "year": 2013 } print(Car) >>>{'brand': 'Ford', 'model': 'Focus', 'year': 2013}
|
The dict() Constructorthisdict = dict(brand="Ford", model="Focus", year=2013)
|
Accessing ItemsExample 1 x = Car["model"] Example 2 x = Car.get("model") |
Check if Key ExistsCheck if "year" is present in the dictionary: if "year" in Car: print("Yes, 'year' is one of the keys in the Car dictionary") |
Adding ItemsCar["Combined MPG"] = 32
|
| | Removing ItemsCar.pop("year")
| The pop() method removes the item with the specified key name | Car.popitem()
| The popitem() method removes the last inserted item | del Car["year"]
| The del keyword removes the item with the specified key name |
Delete a Dictionarydel Car print(Cars) #this will cause an error because "Cars" no longer exists.
|
Return an Empty Dictionary
Copy a DictionaryExample 1 CarCopy = Car.copy() Example 2 CarCopy = dict(Car) |
| | Nested DictionariesCars = { "Car1":{ "brand":"Ford", "model":"Focus" }, "Car2":{ "brand":"Fiat", "model":"Punto" } }
| Create a nested dictionary from two existing dictionairies. | Car1 = { "brand": "Ford", "model": "Focus" } Car2 = { "brand": "Fiat", "model": "Punto" } Cars = { "Car1": Car1, "Car2": Car2 }
|
|
Created By
Metadata
Favourited By
Comments
No comments yet. Add yours below!
Add a Comment
Related Cheat Sheets
More Cheat Sheets by Nouha_Thabet