Introduction to the use of Python dictionary dict

  • 2020-04-02 14:27:33
  • OfStack

The creation of a Python dictionary

Method one:


>>> blank_dict = {}
>>> product_dict = {'MAC':8000,'Iphone':5000, 'ipad':4000, 'mp3': 300}
>>> product_dict
{'ipad': 4000, 'MAC': 8000, 'Iphone': 5000, 'mp3': 300}
>>> blank_dict,product_dict
({}, {'ipad': 4000, 'MAC': 8000, 'Iphone': 5000, 'mp3': 300})

Method 2:
Start with Python 2.2


>>> fdict = dict((['www','www.linuxeye.com'],['blog','blog.linuxeye.com']))
>>> fdict
{'blog': 'blog.linuxeye.com', 'www': 'www.linuxeye.com'}

Method 3:
Starting with Python 2.3, you can use a handy built-in method fromkeys() to create a "default" dictionary with the same value for the elements in the dictionary (default to None if not given):


>>> fk_dict = {}.fromkeys(('a','b'),'LinuxEye')
>>> fk_dict
{'a': 'LinuxEye', 'b': 'LinuxEye'}
>>> fk2_dict = {}.fromkeys(('yeho','python'))
>>> fk2_dict
{'python': None, 'yeho': None}
>>> fk3_dict = {}.fromkeys('yeho','python')
>>> fk3_dict
{'y': 'python', 'h': 'python', 'e': 'python', 'o': 'python'}

The Python dictionary looks up, adds, deletes, and changes


>>> product_dict = {'MAC':8000,'Iphone':5000, 'mp3': 300}
>>> product_dict['Iphone']
5000
>>> product_dict['ipad'] = 4000 # increase 
>>> product_dict
{'ipad': 4000, 'MAC': 8000, 'Iphone': 5000, 'mp3': 300}
 
>>> product_dict.keys() # View index 
['ipad', 'MAC', 'Iphone', 'mp3']
>>> product_dict.values() # See the value 
[4000, 8000, 5000, 300]
>>> product_dict.items()
[('ipad', 4000), ('MAC', 8000), ('Iphone', 5000), ('mp3', 300)]
>>> for product,price in product_dict.items():
...  print product,price
...
ipad 4000
MAC 8000
Iphone 5000
mp3 300
>>> product_dict.has_key('Iphone') # judge key If there is a 
True
>>> product_dict.has_key('Itouch')
False
 
>>> product_dict.pop('MAC') # Delete the specified key and value
 8000
 >>> product_dict
 {'ipad': 4000, 'Iphone': 5000, 'mp3': 300}
 >>> product_dict.popitem() # Delete the first one key and value
 ('ipad', 4000)
 >>> product_dict
 {'Iphone': 5000, 'mp3': 300}
 
 >>> product_dict = {'Iphone': 5000, 'mp3': 300}
 >>> del product_dict['Iphone'] # with del Function deletion specification key and value
 >>> product_dict
 {'mp3': 300}
 >>> product_dict['mp3'] = 299 # change 
 >>> product_dict
 {'mp3': 299}
 >>> product_dict.clear() # Empty dictionary contents (empty dictionary) 
 >>> product_dict
 {}
 >>> del product_dict # To delete a dictionary 
 >>> product_dict = {'mp3': 300}
 >>> del product_dict # Error reported deleted 
 Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
 NameError: name 'product_dict' is not defined

Related articles: