python dictionary comprehension example
---------------1
>>> l1 = ['a', 'b', 'c', 'd']
>>>
>>> dt = {x:2 for x in l1}
>>>
>>> dt
{'a': 2, 'c': 2, 'b': 2, 'd': 2}
>>>
----------------2
>>> l1 = ['a', 'b', 'c', 'd']
>>>
>>> l2 = [1,2,3,4]
>>>
>>>
>>> dt = {x:y for x,y in zip(l1,l2)}
>>>
>>> dt
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>>
----------------3
>>> dt = {i : chr(65+i) for i in range(4)}
>>>
>>> dt
{0: 'A', 1: 'B', 2: 'C', 3: 'D'}
>>>
----------------4
>>> dt = dict([(i, chr(65+i)) for i in range(4)])
>>>
>>> dt
{0: 'A', 1: 'B', 2: 'C', 3: 'D'}
>>>
No comments:
Post a Comment