Posts

Showing posts from March, 2018

OrderedDict in Python

Image
   Concept An  OrderedDict  is a dictionary subclass that remembers the order that keys were first inserted. OrderedDict  preserves the order  in which the keys are inserted. A regular dict doesn’t track the insertion order and iterating it gives the values in an arbitrary order. Code from collections import OrderedDict od = OrderedDict() od['1'] = 5 od['2'] = 4 od['3'] = 3 od['4'] = 2 od['5'] = 1 Get Help

Dict Data Type in Python

Image
Concept Dictionary  is a collection which is unordered, changeable and indexed. No duplicate members Code Example >>> d = {} >>> type(d) <class 'dict'> >>> d = {'key': 'value'} >>> d {'key': 'value'} >>> d = {'1': 1, '2': 2} >>> d {'1': 1, '2': 2} >>> l = [10, 20] >>> d.update({'l1': l}) >>> d {'1': 1, '2': 2, 'l1': [10, 20]} # data within dict [Tested on IDLE ] >>> l = [1, 2, 3, 4] >>> d1 = {1: 'A', 2: 'a'} >>> t = (1, 2) >>> s = {1, 2}  >>> d = {'1': 1, '2': l, '3': d1, '4': t, '5': s} >>> d {'1': 1, '2': [1, 2, 3, 4], '3': {1: 'A', 2: 'a'}, '4': (1, 2), '5': {1, 2}}  >>> d['3'][1] 'A'  >>> d = {i: i

Convert Nested List To Flat List

Image
  Code Suppose you have a list like : [[1], [2,3], [4, [5, 6]], [7], [8], [9], [10]] Now if I want to make it a flat list like : [1,2,3,4,5,6,7,8,9] How can we do that?  😕  Don't worry dear, there are many ways to do so. You are going to take help one builtin lib of python 😍 # Example from functools import reduce >>> l = [[1], [2,3], [4, 5, 6], [7], [8], [9], [10]] >>> flat_list = reduce(lambda x, y: x+y, l) >>> flat_list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Enjoy Edge-cutting Technology 😉 Get Help

List comprehension in Python

Image
Code Example 1: l = [i for i in range(1, 11, 1)] print(l) Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Example 2: l = [[i, i+1] for i in range(1,6)] print(l) Output: [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] Example 3: l = [i for i in range(1, 11, 1)] print(l) Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Example 4: l = [i for i in range(1,6) if i%2 == 0] print(l) Output: [2, 4] Get Help