Posts

Showing posts with the label python

Combine Python Lists

Combine Python Lists using plus(+) chars = ['a', 'b', 'c'] total_chars = chars + ['d', 'e'] print(total_items) # ['a', 'b', 'c', 'd', 'e'] Note: This approach not work for adding single item to the list, you can use .append(). Another approach to add one item is to create a new list with a single value and then use the plus symbol to add the list.

Pop from Python Dictionary

.pop() Method in Python We can use .pop() method to remove key-value pairs from Python dictionary. This method takes a key as an argument and removes it from the dictionary and it returns the value that it removed from the dictionary. user = {'first_name': 'nishant', 'last_name': 'nigam', 'city': 'Indore'} user.pop('city') print(user) # {'first_name': 'nishant', 'last_name': 'nigam'}

Merge dictionaries in Python

Merge dictionaries in Python with update() address = {'street': 'MG Road', 'house': '123'} contact = {'country': 'India', 'city': 'Indore', 'street': 'Ring Road'} address.update(contact) # Address dictionary will now have the updated data {'house': '123', 'country': 'India', 'city': 'Indore', 'street': 'Ring Road'} We can use update() when we are required to merge two dictionaries in Python address.update(contact), the key-value pairs of contact(dictionary2) will be written into the address(dictionary1).And for keys in both dictionary1 and dictionary2, the value in dictionary1 will be overwritten by the corresponding value in dictionary2

Why to use get(key) instead of [key] for Python Dictionary?

Accessing value from a dictionary using square brackets will raise an exception if there is no value mapped to that key, here is an example >>> dict = {'key1':1,'key2':2} >>> dict['key1'] 1 >>> dict['key3'] Traceback (most recent call last): File "", line 1, in dict['key3'] KeyError: 'key3' On the other hand, 'get' will return the default value if there is no value mapped to that key, the default value is 'None' by default >>> dict = {'key1':1,'key2':2} >>> dict['key1'] 1 >>> a = dict.get('key3) >>> print a 0 To set a custom default value >>> a = dict.get('key3', 'MyCustomValue')