Python dictionary dict usage introduction, pythondict
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 "<stdin>", line 1, in <module> NameError: name 'product _ dict 'is not defined