Python Programming/Dictionaries
From Wikibooks, the open-content textbooks collection
| Previous: Tuples | Index | Next: Sets |
Contents |
[edit] About dictionaries in Python
A dictionary in python is a collection of unordered values which are accessed by key.
[edit] Dictionary notation
Dictionaries may be created directly or converted from sequences. Dictionaries are enclosed in curly braces, {}
>>> d = {'city':'Paris', 'age':38, (102,1650,1601):'A matrix coordinate'} >>> seq = [('city','Paris'), ('age', 38), ((102,1650,1601),'A matrix coordinate')] >>> d {'city': 'Paris', 'age': 38, (102, 1650, 1601): 'A matrix coordinate'} >>> dict(seq) {'city': 'Paris', 'age': 38, (102, 1650, 1601): 'A matrix coordinate'} >>> d == dict(seq) True
Also, dictionaries can be easily created by zipping two sequences.
>>> seq1 = ('a','b','c','d') >>> seq2 = [1,2,3,4] >>> d = dict(zip(seq1,seq2)) >>> d {'a': 1, 'c': 3, 'b': 2, 'd': 4}
[edit] Operations on Dictionaries
The operations on dictionaries are somewhat unique. Slicing is not supported, since the items have no intrinsic order.
>>> d = {'a':1,'b':2, 'cat':'Fluffers'} >>> d.keys() ['a', 'b', 'cat'] >>> d.values() [1, 2, 'Fluffers'] >>> d['a'] 1 >>> d['cat'] = 'Mr. Whiskers' >>> d['cat'] 'Mr. Whiskers' >>> d.has_key('cat') True >>> d.has_key('dog') False >>> 'cat' in d True
[edit] Combining two Dictionaries
You can combine two dictionaries by using the update method of the primary dictionary. Note that the update method will merge existing elements if they conflict.
>>> d = {'apples': 1, 'oranges': 3, 'pears': 2} >>> ud = {'pears': 4, 'grapes': 5, 'lemons': 6} >>> d.update(ud) >>> d {'grapes': 5, 'pears': 4, 'lemons': 6, 'apples': 1, 'oranges': 3} >>>
[edit] Deleting from dictionary
del dictionaryName[membername]
| Previous: Tuples | Index | Next: Sets |