17
loading...
This website collects cookies to deliver better user experience
dictionaries
in python,dict1 = {"name": "Salman", "age": "NA"}
dict2 = {"crimes": "lol", "career_destroyed": "uncountable"}
# Way1 : using update method
dict1.update(dict2)
print("dict1 =>", dict1)
# Way2: using ugly ** unpacking
new_dict = {**dict1, **dict2}
print("new_dict=>", new_dict)
"""OUPUT
dict1 => {'name': 'Salman', 'age': 'NA',
'crimes': 'lol', 'career_destroyed': 'uncountable'}
new_dict=> {'name': 'Salman', 'age': 'NA',
'crimes': 'lol', 'career_destroyed': 'uncountable'}
"""
d1.update(d2)
modifies d1 in-place i.e changes the content of d1 dictionary.😛 Then why don't we use ** , because it is not readable and ugly!
dict
consisting of the left operand merged with the right operand, each of which must be a dict.# removing prefix or suffix prior to python 3.9
def remove_prefix(inp_str: str, pref: str) -> str:
"""
This function deletes "pref" from the
beginning if it is present otherwise
returns the original "inp_str"
"""
if inp_str.startswith(pref):
return inp_str[len(pref):]
return inp_str
def remove_suffix(inp_str: str, suff: str) -> str:
"""
This function deletes "suff" from the
end if it is present otherwise
returns the original "inp_str"
"""
if inp_str.endswith(suff):
return inp_str[:-len(suff)]
return inp_str
"""OUTPUT
>>> remove_suffix("Kathan", "an")
'Kath'
>>> remove_suffix("Kathan", "lol")
'Kathan'
>>> remove_prefix("Kathan","Ka")
'than'
>>> remove_prefix("Kathan","haha")
'Kathan'
"""
lambda
but what if you want a cleaner solution?