Posts

Showing posts with the label dict

Dict Comprehension in Python

Image
  Code Example Example 1: d = {i:i for i in range(1, 6)} print(d) Output: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5}   Example 2: d = {i:[i, i+1] for i in range(6)} print(d) Output: {0: [0, 1], 1: [1, 2], 2: [2, 3], 3: [3, 4], 4: [4, 5], 5: [5, 6]}   Example 3: d = {i:i**2 for i in range(6)} print(d) Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} Get Help

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...