Dictionary in Python
Dictionary
is used to represent a collection of keys and values pair of data.
Syntax
fruitsCollection=
{'apple', 'pear', 'orange', 'banana'}
print
fruitsCollection
output
set(['orange',
'pear', 'banana', 'apple'])
userCollection
= {'1': 'Mac', '2': 'ALEN','3':'Kenneth'}
del
userCollection['1']
print
userCollection
output
{'3':
'Kenneth', '2': 'ALEN'}
for
i, j in userCollection.items():
print(i,j)
Output
('3',
'Kenneth')
('2',
'ALEN')
Dictionary
Manipulation functions
dict1
= { } Empty
dictionary
dict2
= {'Aa': 2, 'Bb': 3} Two-item dictionary
dict2['session'] Indexing
by key
dict2.has_key('UserName'), UserName' in dict2 membership test
dict2.keys(
), dict2.values( ),
dict2.items(
) lists
of keys, values, items
dict2.copy(
),
dict2.update(dict1) shallow
copy, dict merging
dict2.get(key,
default=None) "indexing"
len(dict1) Length
(number stored entries)
dict2[key]
= 300 Adding/changing
del
dict2[key] deleting
dict
= dict(zip(klist, vlist)) Construction
Dictionary in Python
Reviewed by Rupesh
on
10:15
Rating:
No comments: