Cheatography
https://cheatography.com
Dictionary
A dictionary is changeable and indexed like a list and unordred like a set. A dictionairy contains keys and values. |
Dictionary example
Car = { "brand": "Ford", "model": "Focus", "year": 2013 } print(Car) >>>{'brand': 'Ford', 'model': 'Focus', 'year': 2013}
|
The dict() Constructor
thisdict = dict(brand="Ford", model="Focus", year=2013)
|
Accessing Items
Example 1 x = Car["model"] Example 2 x = Car.get("model")
|
Check if Key Exists
Check if "year" is present in the dictionary: if "year" in Car: print("Yes, 'year' is one of the keys in the Car dictionary")
|
Adding Items
Car["Combined MPG"] = 32
|
|
|
Removing Items
|
The pop()
method removes the item with the specified key name |
|
The popitem()
method removes the last inserted item |
|
The del
keyword removes the item with the specified key name |
Delete a Dictionary
del Car print(Cars) #this will cause an error because "Cars" no longer exists.
|
Return an Empty Dictionary
Copy a Dictionary
Example 1 CarCopy = Car.copy() Example 2 CarCopy = dict(Car)
|
|
|
Nested Dictionaries
Cars = { "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