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 ①:
- >>> dict1 = {}
- >>> dict2 = {'name': 'earth', 'port': 80}
- >>> dict1, dict2
- ({}, {'port': 80, 'name': 'earth'})
Method 2: Start With Python 2.2
- >>> fdict = dict((['x', 1], ['y', 2]))
- >>> fdict
- {'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 ):
- >>> ddict = {}.fromkeys(('x', 'y'), -1)
- >>> ddict
- {'y': -1, 'x': -1}
- >>>
- >>> edict = {}.fromkeys(('foo', 'bar'))
- >>> edict
- {'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:
- >>> dict2 = {'name': 'earth', 'port': 80}
- >>>
- >>>> for key in dict2.keys():
- ... print 'key=%s, value=%s' % (key, dict2[key])
- ...
- key=name, value=earth
- key=port, value=80
② Traverse the dictionary in the for loop from Python 2.2.
- >>> dict2 = {'name': 'earth', 'port': 80}
- >>>
- >>>> for key in dict2:
- ... print 'key=%s, value=%s' % (key, dict2[key])
- ...
- key=name, value=earth
- 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:
- >>> dict2['name']
- 'earth'
- >>>
- >>> print 'host %s is running on port %d' % \
- ... (dict2['name'], dict2['port'])
- host earth is running on port 80
③ Dictionary all methods. Methods has_key (), in, and not in are boolean operators.
- >>> 'Server' in dict2 # Or dict2.has _ key ('server ')
- False
- >>> 'Name' in dict # Or dict2.has _ key ('name ')
- True
- >>> Dict2 ['name']
- 'Global'
An example of mixing numbers and strings in a dictionary:
- >>> dict3 = {}
- >>> dict3[1] = 'abc'
- >>> dict3['1'] = 3.14159
- >>> dict3[3.2] = 'xyz'
- >>> dict3
- {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.