python· challenge2

5.5. Dictionaries

Another useful data type built into Python is the dictionary (see Mapping Types — dict). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed bykeys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within onedictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.

The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it). To check whether a single key is in the dictionary, use the in keyword.

Here is a small example using a dictionary:

>>>
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> tel.keys()
['guido', 'irv', 'jack']
>>> 'guido' in tel
True

The dict() constructor builds dictionaries directly from sequences of key-value pairs:

>>>
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}

In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

>>>
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

>>>
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}

第一次:
 1 # -*- coding: utf-8 -*-
 2 __author__ = 'hcs'
 3 
 4 f = open("1.txt","r")
 5 a = {}
 6 for char in f:
 7     if (char!="/0") and (char != " "):
 8         if char not in a.keys():
 9             a[char] = 1;
10         else:
11             a[char] += 1;
12 
13 for i in a:
14     print " %s : %d" %(i,a[i])

结果是输出每一行的字典。其实应该再加一个循环:

 1 # -*- coding: utf-8 -*-
 2 __author__ = 'hcs'
 3 
 4 f = open("1.txt","r")
 5 a = {}
 6 for line in f:     #新增代码
 7     for char in line:    
 8         if (char!="/0") and (char != " "):
 9             if char not in a.keys():
10                 a[char] = 1;
11             else:
12                 a[char] += 1;
13 
14 for i in a:
15     print " %s : %d" %(i,a[i])

输出结果:

_ : 6112
^ : 6030
a : 1
e : 1
i : 1
l : 1
q : 1
u : 1
t : 1
y : 1
{ : 6046
} : 6105

可以看出组合是equality



posted @ 2014-11-17 15:47  hcs2024  阅读(227)  评论(0编辑  收藏  举报