My friends, for reprint please indicate the source: blog.csdn.net/jiangjunsho…
Disclaimer: During the teaching of artificial intelligence technology, many students asked me some python related questions, so in order to let students master more extended knowledge and better understand AI technology, I asked my assistant to share this Python series of tutorials, hoping to help you! Since this Python tutorial is not written by me, it is not as funny and boring as my AI teaching. But its knowledge points or say in place, also worth reading! If you want to learn AI technology, you can click on my teaching website. PS: if you don’t understand this article, please read the previous article first. Step by step, you won’t feel difficult to learn a little every day!
The ZIP call can also be used to produce dictionaries when collections of keys and values must be evaluated at run time, and is very convenient to use.
Here is a common way to create a dictionary.
>>> D1 = {'spam':1,'eggs':3,'toast':5}
>>> D1
{'toast': 5,'eggs': 3,'spam': 1}
>>> D1 = {}
>>> D1['spam'] = 1
>>> D1['eggs'] = 3
>>> D1['toast'] = 5
Copy the code
What if your program gets a list of dictionary keys and values at run time after the script has been written? For example, suppose you have the following list of keys and values:
> > > keys = [' spam ', 'dense eggs',' toast '] > > > vals =,3,5 [1]Copy the code
One way to turn these lists into dictionaries is to zip up the strings and step through them in parallel through a for loop.
>> list (keys,vals) [('spam',1), ('eggs',3), ('toast',5)] >>> D2 = {} >>> for (k,v) in zip (keys,vals) : D2[k] = v... >>> D2 {'toast': 5,'eggs': 3,'spam': 1}Copy the code
Additionally, in Python 2.2 and later, you can skip the for loop entirely and pass the zipped list of keys/values directly to the built-in dict constructor.
> > > keys = [' spam ', 'dense eggs',' toast '] > > > vals,3,5 [1] = > > > D3 = dict (zip (keys, vals)) > > > D3 {' toast '5,' dense eggs' : 3,'spam': 1}Copy the code