Python Working With Dict Data Type¶
Lets start working with dict data type in python. Dictionary is collection of unordered set of key, value pairs. We can create an empty dictionary with the empty braces {}. dict data type in python is one of the most used datatypes in python builtin data types. We can only able to use keys which are in immutable nature. i.e. we can use string, tuple, numbers as keys. But, we cannot use lists, sets, etc. dict is a mutable data type in python.
Basic operations of python dictionary(dict)¶
- Creating a dictionary(dict)
# empty dict using curly braces
d1 = {}
# empty dict using builtin dict function
d2 = dict()
# create dict from list of key, value pairs
d3 = dict([(1,2), ("hi", "hello")])
print(d3)
# output: {1: 2, 'hi': 'hello'}
# create dict from kwargs
d4 = dict(hi="hello", hello="hi")
print(d4)
# output: {'hello': 'hi', 'hi': 'hello'}
- Add a key to dictionary(dict)
d1 = {}
# add key "hi" with value "hello" to dict d1
d1["hi"] = "hello"
print(d1)
# output: {"hi": "hello"}
It will raises an error if key is not found.
- Get key from dictionary(dict)
d1 = {"hi": "hello"}
# get key value from dict d1
val = d1["hi"]
print(val)
# output: "hello"
- Remove a key from the dictionary(dict)
d1 = {"hi": "hello", "me": "anji"}
del d1["me"]
print(d1)
# output: {'hi': 'hello'}
It will raises an error if the is not present .
Working with dictionary(dict) methods in python¶
- Working with "clear" method in dict
# D.clear() -> None. Remove all items from D.
d1 = {"hi": "hello", "me": "anji"}
d1.clear()
print(d1)
# output: {}
- Working with "copy" method in dict
# D.copy() -> a shallow copy of D
d1 = {"hi": "hello"}
d2 = d1.copy()
print(d2)
# output: {'hi': 'hello'}
print(id(d1), id(d2))
# output: 140645374610760 140645374610440
- Working with "fromkeys" method in dict
# dict.fromkeys(seq[, value]) --> dict
keys = ("ram", "robert", "raheem")
d1 = dict.fromkeys(keys)
print(d1)
# output: {'ram': None, 'robert': None, 'raheem': None}
d2 = dict.fromkeys(keys, 100)
print(d2)
# output: {'ram': 100, 'robert': 100, 'raheem': 100}
It takes iterable set of elements and a value as an argument and creates the dictionary with keys and value will be same. If default value is not given then it takes the value as None.
- Working with "get" method in dict
# D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
d1 = {"hi": "hi", "hello": 125}
v1 = d1.get("hello")
print(v1)
# output: 125
v2 = d1.get("invalid_key")
print(v2)
# output: None
v3 = d1.get("invalid_key", 100)
print(v3)
# output: 100
- Working with "items" method in dict
# D.items() -> a set-like object providing a view on D's items
d1 = {"a": 1, "b": 2, "c": 3}
result = d1.items()
print(result)
# output: dict_items([('c', 3), ('b', 2), ('a', 1)])
It returns all the values as set of tuples with key, value as a pair. The returning data type is dict-items. It is a set-like object.
- Working with "keys" method in dict
# D.keys() -> a set-like object providing a view on D's keys
d1 = {"a": 1, "b": 2, "c": 3}
result = d1.keys()
print(result)
# output: dict_keys(['c', 'b', 'a'])
It returns the set-like object which contains all the keys of the dict.
- Working with "pop" method in dict
# D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
d1 = {"a": 1, "b": 2, "c": 3}
result = d1.pop("a")
print(result)
# output: 1
print(d1)
# output: {'c': 3, 'b': 2}
result = d1.pop("a1")
# output: KeyError
result = d1.pop("a1", 100)
print(result)
# output: 100
If key is not found, d is returned if given, otherwise KeyError is raised. If key not found and default is provided then default will be returned.
- Working with "popitem" method in dict
# D.popitem() -> (k, v)
# remove and return some (key, value) pair as a 2-tuple;
# but raise KeyError if D is empty.
d1 = {"a": 1, "b": 2, "c": 3}
result = d1.popitem()
print(result)
# output:
print(d1)
# output: ('c', 3)
d2 = {}
result = d2.popitem()
# output: KeyError
- Working with "setdefault" method in dict
# D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
- Working with "update" method in dict
# D.update([E, ]**F) -> None.
d1 = {"a": 1, "b": 2, "c": 3}
d2 = {"a": 10, "d": 100, "e": 120}
d1.update(d2)
print(d1)
# output: {'d': 100, 'c': 3, 'b': 2, 'e': 120, 'a': 10}
d1 = {"a": 1}
d2 = {"b": 2, "c": 3}
d1.update(d2, z=26)
print(d1)
# output: {'z': 26, 'c': 3, 'b': 2, 'a': 1}
Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]. If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v. In either case, this is followed by: for k in F: D[k] = F[k].
- Working with "values" method in dict
# D.values() -> an object providing a view on D's values
d1 = {"a": 1, "b": 2, "c": 3}
result = d1.values()
print(result)
# output: dict_values([3, 2, 1])
It returns an set like object which contains all the values of the dictionary.
Rerefences: https://docs.python.org/3/tutorial/datastructures.html#dictionaries