The example in this article describes how Python implements a dictionary creation without excessive invocation. Share to everyone for your reference. The implementation method is as follows:
1. Using the Itertools module
Import Itertoolsthe_key = [' ab ', ' $ ', 33]the_vale = [' aaaa ', ' dddddddd ', ' 22222222222 ']d = Dict (Itertools.izip (The_key, The_vale)) Print D
2. Add parameter
Dict = dict (red = 1,bule = 2,yellow = 3) Print Dict
The result is: {' Yellow ': 3, ' Bule ': 2, ' Red ': 1}
3. Using the built-in zip function
Zip ([iterable,...]) Returns a list of
The_key = [' ab ', ' $ ', 33]the_vale = [' aaaa ', ' dddddddd ', ' 22222222222 ']dict2 = dict (Zip (the_key,the_vale)) ' Print type ' (zip (The_key,the_vale)) Print Dict2
Results:
{: ' 22222222222 ', ' ab ': ' AAAA ', ' $ ': ' dddddddd '}
The Fromkeys function of 4.dict
Each key created has the same value
Result: {33:0, ' ab ': 0, ' 22 ': 0}
Import Stringcount_by_letter = Dict.fromkeys (string.ascii_lowercase,0) Print Count_by_letter
Results:
{' A ': 0, ' C ': 0, ' B ': 0, ' E ': 0, ' d ': 0, ' G ': 0, ' F ': 0, ' I ': 0, ' h ': 0, ' K ': 0, ' J ': 0, ' m ': 0, ' l ': 0, ' O ': 0, ' n ': 0, ' Q ': 0, ' P ': 0, ' s ': 0, ' R ': 0, ' U ': 0, ' t ': 0, ' W ': 0, ' V ': 0, ' y ': 0, ' X ': 0, ' Z ': 0}
I hope this article is helpful to the study of Python program design.