Python Dictionaries Sets
Python Dictionaries Sets
Dictionaries in Python
A dictionary is a collection of key-value pairs. It is defined using {}.
dict.keys()
Returns all the keys in the dictionary.
Example: student.keys()
dict.values()
Returns all the values in the dictionary.
Example: student.values()
dict.items()
Returns key-value pairs as tuples.
Example: student.items()
dict.get(key)
Returns the value for the given key.
Example: student.get("name")
dict.update(new_dict)
Updates the dictionary with another dictionary.
Example: student.update({"marks": 90})
dict.pop(key)
Removes a key and returns its value.
Example: student.pop("age")
dict.popitem()
Removes the last key-value pair.
Example: student.popitem()
dict.clear()
Removes all items from the dictionary.
Example: student.clear()
Examples:
student = {"name": "John", "age": 16, "marks": 85}
print(student.keys()) # dict_keys(['name', 'age', 'marks'])
print(student.values()) # dict_values(['John', 16, 85])
print(student.items()) # dict_items([('name', 'John'), ('age', 16), ('marks', 85)])
Sets in Python
A set is a collection of unique elements. It is defined using {}.
set.add(value)
Adds an element to the set.
Example: numbers.add(5)
set.remove(value)
Removes an element from the set.
Example: numbers.remove(3)
set.discard(value)
Removes an element (no error if missing).
Example: numbers.discard(7)
set.pop()
Removes a random element.
Example: numbers.pop()
set.clear()
Removes all elements from the set.
Example: numbers.clear()
set.union(set2)
Returns a new set with elements from both sets.
Example: A.union(B)
set.intersection(set2)
Returns common elements in both sets.
Example: A.intersection(B)
set.difference(set2)
Returns elements in the first set but not in the second.
Example: A.difference(B)
set.issubset(set2)
Checks if the first set is a subset of the second.
Example: A.issubset(B)
set.issuperset(set2)
Checks if the first set is a superset of the second.
Example: A.issuperset(B)
Examples:
numbers = {1, 2, 3, 4}
numbers.add(5)
print(numbers) # {1, 2, 3, 4, 5}
print(numbers.union({6, 7})) # {1, 2, 3, 4, 5, 6, 7}
print(numbers.intersection({3, 4, 5})) # {3, 4, 5}