Three methods for creating a Python dictionary

Source: Internet
Author: User

If you have any questions about how to create a Python dictionary and how to access the values in the dictionary, you can browse our article, after reading this article, I hope you will learn something from it. The following describes the specific content of this article.

Create a Python dictionary

Method ①:

 
 
  1. >>> dict1 = {}  
  2. >>> dict2 = {'name': 'earth', 'port': 80}  
  3. >>> dict1, dict2  
  4. ({}, {'port': 80, 'name': 'earth'})  

Method 2: Start With Python 2.2

 
 
  1. >>> fdict = dict((['x', 1], ['y', 2]))  
  2. >>> fdict  
  3. {'y': 2, 'x': 1}  

Method ③: from Python 2.3, you can use a convenient built-in method fromkeys () to create a "default" dictionary. The elements in the dictionary have the same value (if not given, the default value is None ):

 
 
  1. >>> ddict = {}.fromkeys(('x', 'y'), -1)  
  2. >>> ddict  
  3. {'y': -1, 'x': -1}  
  4. >>> 
  5. >>> edict = {}.fromkeys(('foo', 'bar'))  
  6. >>> edict  
  7. {'foo': None, 'bar': None}  

How to access values in the dictionary

① To traverse a dictionary (usually using a key), you only need to view its key cyclically, as shown in the following code:

 
 
  1. >>> dict2 = {'name': 'earth', 'port': 80}  
  2. >>> 
  3. >>>> for key in dict2.keys():  
  4. ... print 'key=%s, value=%s' % (key, dict2[key])  
  5. ...  
  6. key=name, value=earth 
  7. key=port, value=80 

② Traverse the dictionary in the for loop from Python 2.2.

 
 
  1. >>> dict2 = {'name': 'earth', 'port': 80}  
  2. >>> 
  3. >>>> for key in dict2:  
  4. ... print 'key=%s, value=%s' % (key, dict2[key])  
  5. ...  
  6. key=name, value=earth 
  7. key=port, value=80 

To get the value of an element in the Python dictionary, you can use the dictionary key you are familiar with and brackets to get it:

 
 
  1. >>> dict2['name']  
  2. 'earth'  
  3. >>> 
  4. >>> print 'host %s is running on port %d' % \  
  5. ... (dict2['name'], dict2['port'])  
  6. host earth is running on port 80  

③ Dictionary all methods. Methods has_key (), in, and not in are boolean operators.

 
 
  1. >>> 'Server' in dict2 # Or dict2.has _ key ('server ')
  2. False
  3. >>> 'Name' in dict # Or dict2.has _ key ('name ')
  4. True
  5. >>> Dict2 ['name']
  6. 'Global'

An example of mixing numbers and strings in a dictionary:

 
 
  1. >>> dict3 = {}  
  2. >>> dict3[1] = 'abc'  
  3. >>> dict3['1'] = 3.14159  
  4. >>> dict3[3.2] = 'xyz'  
  5. >>> dict3  
  6. {3.2: 'xyz', 1: 'abc', '1': 3.14159}  

The above article introduces how to apply the Python dictionary and how to access the values in the dictionary.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.