Python Dict Functions
Python Dict Functions
keys() Returns all keys in the dictionary dict.keys() {'a': 1, 'b': 2}.keys() -> ['a', 'b']
values() Returns all values in the dictionary dict.values() {'a': 1, 'b': 2}.values() -> [1, 2]
items() Returns all key-value pairs dict.items() {'a': 1, 'b': 2}.items() -> [('a', 1), ('b', 2)]
get() Returns value for key (None if not found) dict.get(key, default) {'a': 1}.get('a') -> 1
update() Updates dictionary with key-value pairs dict.update(other_dict) {'a': 1}.update({'b': 2}) -> {'a': 1, 'b': 2}
setdefault() Returns value if key exists, else sets defaultdict.setdefault(key, default) {'a': 1}.setdefault('b', 2) -> {'a': 1, 'b': 2}
pop() Removes key and returns value dict.pop(key, default) {'a': 1}.pop('a') -> 1, {}
popitem() Removes and returns last key-value pair dict.popitem() {'a': 1, 'b': 2}.popitem() -> ('b', 2)
del Deletes a key from dictionary del dict[key] del d['a'] -> removes 'a' from d
clear() Removes all items from the dictionary dict.clear() {'a': 1, 'b': 2}.clear() -> {}
len() Returns number of key-value pairs len(dict) len({'a': 1, 'b': 2}) -> 2
dict() Creates a new dictionary dict(iterable) dict([('a', 1), ('b', 2)]) -> {'a': 1, 'b': 2}