7-1 字典方法。
哪个字典方法可以用来把两个字典合并到一起?
update() 方法可以实现。
>>> myDict = {'name': 'earth', 'port': '8080'}
>>> myDict
{'name': 'earth', 'port': '8080'}
>>> yourDict = {'language':'Python'}
>>> yourDict
{'language': 'Python'}
>>> myDict.update(yourDict)
>>> myDict
{'name': 'earth', 'language': 'Python', 'port': '8080'}
7-3 字典和列表的方法。
(a) 创建一个字典,并把这个字典中的键按照字母顺序显示出来。
(b) 现在根据已按照字母顺序排序好的键,显示出这个字典中的键和值。
(c)同(b),但这次是根据已按照字母顺序排序好的字典的值,显示出这个字典中的键和值。(注意:对字典和哈希表来说,这样做一般没有什么实际意义,因为大多数访问和排序(如果需要)都是基于字典的键,这里只把它作为一个练习。)
>>> for key in sorted(myDict):
print "key: ", key, ", value: ", myDict[key]
key: 1 , value: one
key: 2 , value: two
key: 3 , value: three
key: 4 , value: four
key: 5 , value: five
key: 6 , value: six
>>> for value in sorted(myDict.values()):
for key in myDict.keys():
if myDict[key] == value:
print "key: ", key, ", value: ", value
key: 5 , value: five
key: 4 , value: four
key: 1 , value: one
key: 6 , value: six
key: 3 , value: three
key: 2 , value: two
7-4 建立字典。
给定两个长度相同的列表,比如说,列表[1, 2, 3,...]和['abc', 'def', 'ghi',...],用这两个列表里的所有数据组成一个字典,像这样:{1:'abc', 2: 'def', 3: 'ghi',...}。
>>> myDict = {}
>>> keys = [1, 2, 3, 4, 5]
>>> values = ['Hello', 'world!', 'This', 'is', 'Python']
>>> for i in range(len(keys)):
myDict[keys[i]] = values[i]
>>> myDict
{1: 'Hello', 2: 'world!', 3: 'This', 4: 'is', 5: 'Python'}