Dictionary and Sets in Python
Dictionary
d={
"key1":"value1"
"key2":"value2"
}
d[key1] # output = value1 # will show error if key is incorrect
Keys need to be of immutable data types eg, string,tuple or int
every key is unique,d is unordered [so no indexing]**,mutable
Dictionary methods:
d.keys()==print value of all keys as list (class=dict_keys) (list)
output as dict_keys([list of keys])
d.values()==print all the values(list)
output as dict_values([list of values])
d.items()== create a list of multiple tuples each having 2 elements :1 key and 1 value.
output as dict_items([list of tuples])
d.update(d2)==add new item(s) of d2 in original dictionary at the end.
or d[new_key]=new_value
d.update("old_key","new_value")==replaces old value with new value
d.get("key",error_message/value)== shows the related value or none # no error[default error message=None]
print(d.get(...))
d.pop("key")
d.clear()
d.fromkeys(<a list of keys>,default_value_to_be_assigned)==create a new dict(if empty then default value ==None)
d2=d1.copy() [deep copy]
s=d.popitem()==removes last key-value pair and assign it to s as tuple(maybe)
max,min, sum, in operator -works on key only
list1=sorted(d)
variable=d.setdefault("key","default_value")==when variable will be called it will return the value of key in dict if it exists else the default_value
for i in d: ==iterate for each key
while creating a dict. if their is repeated key then it will overwrite the previous value the the assigned value to the key will be the last entered value
len(d) and str(d) are valid functions
Merge two dictionaries
For Python 3.5+:
>>> dict_a = {'a': 1, 'b': 2}
>>> dict_b = {'b': 3, 'c': 4}
>>> dict_c = {**dict_a, **dict_b}
>>> dict_c
# {'a': 1, 'b': 3, 'c': 4}
SET
s={1,2,3,4,1}
print(s)={1,2,3,4} #repetitive elements will be ignored
s.add(something) # can add tuple ,can't add list or dict (only add hashable contents)
unordered,unindexed,immutable
len()== give the number of elements
remove(8) : Updates the set S and removes 8 from S
pop() : Removes an arbitrary element from the set and returns the element removed.
clear() : Empties the set S
union({8, 11}) : Returns a new set with all items from both sets. #{1,8,2,3,11}
intersection({8, 11}) : Returns a set which contains only items in both sets. #{8}
Comments
Post a Comment
For any queries or suggestions
Comment Here