Python Programming/Dictionaries
From Wikibooks, open books for an open world
A dictionary in Python is a collection of unordered values which are accessed by key.
Contents |
Dictionary notation [edit]
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}
Operations on Dictionaries [edit]
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' >>> 'cat' in d True >>> 'dog' in d False
Combining two Dictionaries [edit]
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} >>>
Deleting from dictionary [edit]
del dictionaryName[membername]
External links [edit]
- Python documentation, chapter "Dictionaries" -- python.org