Dictionaries
# Dictionaries are used to store data in key value pairs and cannot have duplicate keys
# Define a dictionary
dict1 = {"a":1, "b":2, "c":3}
# Multiple values to a key
employees = {"Finance": ["Bob", "Linda", "Tina"], "IT": ["Gene", "Louise", "Tedy"]}
# Add a key value pair
employees["Legal"] = ["Mr.Frond"]
emplyees.update({"Sales": ["Andie", "Ollie"]})
# Access values in a dictionary
print(dict1["a"])
print(dict1.get("a"))
# Get all keys in dict
print(dict1.keys())
# Get all values
print(dict1.values())
# Print all items
print(dict1.items())
# Change a key value
dict["a"] = 0
dict1.update({"a": 1})
# Remove items from dict
dict1.pop("d")
# Nested dict
dict['c'] = {"a":1, "b":2}
Last updated