python 循环遍历字典元素,Python创建空字典 - 小众知识

python 循环遍历字典元素,Python创建空字典

2015-09-25 15:42:02 苏内容
  标签: python/字典/遍历
阅读:5519

 一个简单的for语句就能循环字典的所有键,就像处理序列一样:


In [1]: d = {'x':1, 'y':2, 'z':3}

In [2]: for key in d:
   ...:     print key, 'corresponds to', d[key]
   ...:
y corresponds to 2
x corresponds to 1
z corresponds to 3

  在python2.2之前,还只能用beys等字典方法来获取键(因为不允许直接迭代字典)。如果只需要值,可以使用d.values代替d.keys。d.items方法会将键-值对作为元组返回,for循环的一大好处就是可以循环中使用序列解包:


In [4]: for key, value in d.items():
   ...:     print key, 'corresponds to', value
   ...:
y corresponds to 2
x corresponds to 1
z corresponds to 3

注意:字典元素的顺序通常没有定义。换句话说,迭代的时候,字典中的键和值都能保证被处理,但是处理顺序不确定。如果顺序很重要的话,可以将键值保存在单独的列表中,例如迭代前进行排序。


'''

 

字典是python中唯一内建的映射类型。字典中的值并没有特殊的顺序,但是都存储在一个特定的键(key)里。
键可以是数字,字符串甚至是元组。
1. 创建和使用字典
字典可以通过下面的方式创建:
复制代码 代码如下:

phonebook = {'Alice':'2341','Beth':'9102','Ceil':'3258'}

字典由多个键及与其对应的值构成的对组成。每个键和它的值之间用冒号(:)隔开,项之间用逗号(,)隔开,而整个字典是由一对大括号括起来。空字典:{}

特点:无序,是唯一内置的映射类型。多用于实现哈希表或者关联数组。




key具有唯一性,可以使用固定长度的对象,不能使用列表、字典和包含可变长度类型的元组。访问形式:m[k],k是key。如果找不到,报错:KeyError。
方法和操作如下:
 
项目
功能
len(m)
 Key的长度
m[k]
 
m[k]=x
 
del m[k]
 
k in m
 有没有k的key
m.clear()
 
m.copy()
 
m.fromkeys(s [,value])
 
m.get(k [,v])
 
m.has_key(k)
 
m.items()
 
m.keys()
 
m.pop(k [,default])
 
m.popitem()
 
m.setdefault(k [, v])
 
m.update(b)
 
m.values()
 
 
*构建字典
 
字典举例:
phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
函数Dict可以从其他映射或者序列构建字典
>>> items = [('name', 'Gumby'), ('age', 42)]
>>> d = dict(items)
>>> d
{'age': 42, 'name': 'Gumby'}
>>> d['name']
'Gumby'
 
       也可以使用参数的方法:
>>> d = dict(name='Gumby', age=42)
>>> d
{'age': 42, 'name': 'Gumby'}
初始化空字典:
>>> x = {}
>>> x[42] = 'Foobar'
>>> x
{42: 'Foobar'}
 
*格式化输出:
>>> phonebook
{'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
>>> "Cecil's phone number is %(Cecil)s." % phonebook
"Cecil's phone number is 3258."
 
 
>>> template = '''
 
 
 
%(title)s
 
%(text)s
 
'''
>>> data = {'title': 'My Home Page', 'text': 'Welcome to my home page!'}
>>> print template % data
 
 
 
 
My Home Page
 
Welcome to my home page!
 
 
另外string.Template 类也很适合这种应用。
 
*字典方法:
-*清除:clear
       下面例子展示clear和把字典置空字典的区别:
>>> x = {}
>>> y = x
>>> x['key'] = 'value'
>>> y
{'key': 'value'}
>>> x = {}
>>> y
{'key': 'value'}
 
 
>>> x = {}
>>> y = x
>>> x['key'] = 'value'
>>> y
{'key': 'value'}
>>> x.clear()
>>> y
{}
 
 
-*复制:copy
 
>>> x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
>>> y = x.copy()
>>> y['username'] = 'mlh'
>>> y['machines'].remove('bar')
>>> y
{'username': 'mlh', 'machines': ['foo', 'baz']}
>>> x
{'username': 'admin', 'machines': ['foo', 'baz']}
 
       浅拷贝的元素指向原有元素,所以改变原有的可变元素,新的也会受影响,反之亦然。换种说法,对元素进行替换,不会对新老都产生影响,但是修改则会有影响。
 
>>> from copy import deepcopy
>>> d = {}
>>> d['names'] = ['Alfred', 'Bertrand']
>>> c = d.copy()
>>> dc = deepcopy(d)
>>> d['names'].append('Clive')
>>> c
{'names': ['Alfred', 'Bertrand', 'Clive']}
>>> dc
{'names': ['Alfred', 'Bertrand']}
 
-*复制key:fromkeys
>>> {}.fromkeys(['name', 'age'])
{'age': None, 'name': None}
       也可以用dict代替{}
>>> dict.fromkeys(['name', 'age'])
{'age': None, 'name': None}
        设置其他默认值:
>>> dict.fromkeys(['name', 'age'], '(unknown)')
{'age': '(unknown)', 'name': '(unknown)'}
 
 
-*获取:get
 
>>> d = {}
>>> print d['name']
Traceback (most recent call last):
File "", line 1, in ?
KeyError: 'name'
>>> print d.get('name')
None
也可以用其他字符替代None
 
>>> d.get('name', 'N/A')
'N/A'
 
-*has_key:是否有key
和k in d是等效的,Python 3.0将取消这个,建议不要使用
>>> d = {}
>>> d.has_key('name')
False
>>> d['name'] = 'Eric'
>>> d.has_key('name')
True
 
-*列出值:items and iteritems
>>> d = {'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}
>>> d.items()
[('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]
 
>>> it = d.iteritems()
>>> it
 
>>> list(it) # Convert the iterator to a list
[('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]
       Iteritems生成迭代器,一般的情况下使用iteritems比iteritem更有效,尤其是循环的时候。
注:Python 3 items 返回的是迭代器
 
-*列出关键字:keys and iterkeys
       后者是迭代器
根据key出栈:pop
>>> d = {'x': 1, 'y': 2}
>>> d.pop('x')
1
>>> d
{'y': 2}
-*出栈:popitem
>>> d
{'url': 'http://www.python.org', 'spam': 0, 'title': 'Python Web Site'}
>>> d.popitem()
('url', 'http://www.python.org')
>>> d
{'spam': 0, 'title': 'Python Web Site'}
       出栈和列表和类似,但是没有append。
-*setdefault:设置默认值。
>>> d = {}
>>> d.setdefault('name', 'N/A')
'N/A'
>>> d
{'name': 'N/A'}
>>> d['name'] = 'Gumby'
>>> d.setdefault('name', 'N/A')
'Gumby'
>>> d
{'name': 'Gumby'}
       默认值的默认值为None。
>>> d = {}
>>> print d.setdefault('name')
None
>>> d
{'name': None}
 
-*更新:update
>>> d = {
'title': 'Python Web Site',
'url': 'http://www.python.org',
'changed': 'Mar 14 22:09:15 MET 2008'
}
>>> x = {'title': 'Python Language Website'}
>>> d.update(x)
>>> d
{'url': 'http://www.python.org', 'changed':
'Mar 14 22:09:15 MET 2008', 'title': 'Python Language Website'}
 
 
-*取值:values and itervalues
 
>>> d = {}
>>> d[1] = 1
>>> d[2] = 2
>>> d[3] = 3
>>> d[4] = 1
>>> d.values()
[1, 2, 3, 1]
 
 
*实例:
存储个人的电话和地址的脚本:
 
# A simple database
 
# A dictionary with person names as keys. Each person is represented as
# another dictionary with the keys 'phone' and 'addr' referring to their phone
# number and address, respectively.
 
people = {
 
    'Alice': {
        'phone': '2341',
        'addr': 'Foo drive 23'
    },
 
    'Beth': {
        'phone': '9102',
        'addr': 'Bar street 42'
    },
 
    'Cecil': {
        'phone': '3158',
        'addr': 'Baz avenue 90'
    }
 
}
 
# Descriptive labels for the phone number and address. These will be used
# when printing the output.
labels = {
    'phone': 'phone number',
    'addr': 'address'
}
 
name = raw_input('Name: ')
 
# Are we looking for a phone number or an address?
request = raw_input('Phone number (p) or address (a)? ')
 
# Use the correct key:
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'
 
# Only try to print information if the name is a valid key in
# our dictionary:
if name in people: print "%s's %s is %s." % \
(name, labels[key], people[name][key])
 
 
将上述例子改为getkey
 
# A simple database
 
# A dictionary with person names as keys. Each person is represented as
# another dictionary with the keys 'phone' and 'addr' referring to their phone
# number and address, respectively.
 
people = {
 
    'Alice': {
        'phone': '2341',
        'addr': 'Foo drive 23'
    },
 
    'Beth': {
        'phone': '9102',
        'addr': 'Bar street 42'
    },
 
    'Cecil': {
        'phone': '3158',
        'addr': 'Baz avenue 90'
    }
 
}
 
 
labels = {
    'phone': 'phone number',
    'addr': 'address'
}
 
name = raw_input('Name: ')
 
# Are we looking for a phone number or an address?
request = raw_input('Phone number (p) or address (a)? ')
 
# Use the correct key:
key = request # In case the request is neither 'p' nor 'a'
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'
 
# Use get to provide default values:
person = people.get(name, {})
label = labels.get(key, key)
result = person.get(key, 'not available')
 
print "%s's %s is %s." % (name, label, result)

扩展阅读
相关阅读
© CopyRight 2010-2021, PREDREAM.ORG, Inc.All Rights Reserved. 京ICP备13045924号-1