Dict Data Type in Python
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**2 for i in range(1, 11, 2)}
>>> d
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
>>>
>>> for i in d:
print(i)
1
3
5
7
9
Comments
Post a Comment