This article describes how to use the Python dictionary dict. For more information, see
Create a Python dictionary
Method 1:
>>> 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:
Starting 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:
From Python 2.3, you can use fromkeys (), a convenient built-in method, to create a "default" Dictionary. the elements in the dictionary have the same value (if not given, the default value is None ):
>>> 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'}
Query, add, delete, and modify Python dictionaries
>>> Product_dict = {'Mac': 8000, 'iPhone ': 5000, 'mp3 ': 300 >>>> product_dict ['iPhone '] 5000 >>>> product_dict ['iPad'] = 4000 # Add >>>> product_dict {'iPad ': 4000, 'Mac ': 8000, 'iPhone ': 5000, 'mp3': 300 }>>> product_dict.keys () # View indexes ['iPad', 'mac', 'iPhone ', 'mp3'] >>> product_dict.values () # view the value [4000,800 0, 5000,300] >>> product_dict.items () [('iPad ', 4000), ('Mac ', 8000), ('iPhone ', 5000), ('mp3', 300)] >>> for product, price in product_dict.items ():... print product, price... ipad 4000MAC 8000 Iphone 5000mp3 300 >>> product_dict.has_key ('iPhone ') # judge whether the key exists 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 key and value ('iPad ', 4000) >>> product_dict {'iPhone': 5000, 'mp3 ': 300 >>>> product_dict = {'iPhone ': 5000, 'mp3 ': 300 >>>> del product_dict ['iPhone '] # Use The del function to delete the specified key and value >>>> product_dict {'mp3 ': 300 >>>> product_dict ['mp3'] = 299 # change >>>> product_dict {'mp3': 299 }>>> product_dict.clear () # clear dictionary content (empty Dictionary) >>> product_dict {}>> del product_dict # delete dictionary >>> product_dict = {'mp3 ': 300 }>>> del product_dict # deleted error Traceback (most recent call last): File"
", Line 1, in
NameError: name 'product _ dict 'is not defined