Dictionaries in Python:¶
1) key and value pair2) Key and value can be any datatype
3) Unordered pair
4) keyError
5) in and not in
6) keys(), values(), items()
7) get(key, user defined return value) -> returns a default value if key doesn't exist.
8) setdefault(key:value) -> sets a value if key doesn't exist
9) pprint.pprit() (pretty print)
10) It's mutable
key and value pair:¶
In [1]:
#dict = {key:value}
#Example:
student = {"mike":25, "alex": 35, "tom": 22,"alice":27}
print(student)
Key and value can be any datatype¶
In [3]:
sample_dict = {"string":"string", "string":10,10:200, 1.02:5.5, 1.09:"check"}
print(sample_dict)
Unordered pair¶
List is an ordered pair, but dictionary is an unordered pair.
In [4]:
a = [1,2,3]
b = [3,2,1]
print(a == b)
class1 = {"mike":25, "alex": 35, "tom": 22,"alice":27}
class2 = {"alice":27,"alex":35,"mike":25,"tom":22}
print(class1 == class2)
KeyError in dict¶
Always check whether the key is in dict before accessing it.
In [5]:
student = {"mike":25, "alex": 35, "tom": 22,"alice":27}
print(student["george"])
In [6]:
if "george" in student:
print(student["george"])
in and not in¶
In [7]:
print("mike" in student)
print("mike" not in student)
print("arun" not in student)
keys(), values(), items()¶
In [8]:
print(student.keys()) # key list
print(student.values()) # value list
print(student.items()) # key,value tuple
In [9]:
for k,v in student.items():
print(k,v)
get() :¶
It returns a default value if key doesn't exist
In [10]:
print(student.get("mike",10))
print(student.get("george",10))
setdefault()¶
In [13]:
student.setdefault("linda",29)
print(student)
student.setdefault("linda",40) # It won't update the value because linda is already in our dict
print(student)
In [16]:
s = "hi how are you? my name is arun prakash."
count_dict = {}
for letter in s:
count_dict.setdefault(letter,0)
count_dict[letter] = count_dict[letter] +1
print(count_dict)
In [17]:
import pprint
pprint.pprint(count_dict)
In [ ]:
No comments :
Post a Comment