Python intensive dictionary introduction
Constructors
d = {} # dict literal notation d = dict() d = {'one': 1, 'two': 2} # dict literal d = dict([('one', 1), ('two', 2)]) # list of tuples d = dict(one=1, two=2) # keyword arguments
Dictionary from key value pair
>>> keys = "one two three".split() >>> values = "1 2 3".split() >>> keys ['one', 'two', 'three'] >>> values ['1', '2', '3'] >>> d = dict(zip(keys, values)) >>> d {'three': '3', 'two': '2', 'one': '1'}
Set default Values
d = dict(zip(keys, [0] * len(keys)))
That's because zip generates tuple. Tuple can convert to list. * means do the same thing as the number.
This is the same to above.
keys = ['one', 'two', 'three'] value = 0 d = dict.fromkeys(keys, value) # builds a dictionary single list of keys