dict.items()和之间是否有任何适用的差异dict.iteritems()?
从Python文档:
dict.items():返回字典的(键,值)对列表的副本.
dict.iteritems():在字典(键,值)对上返回一个迭代器.
如果我运行下面的代码,每个似乎都返回对同一对象的引用.我缺少哪些微妙的差异?
#!/usr/bin/python
d={1:'one',2:'two',3:'three'}
print 'd.items():'
for k,v in d.items():
if d[k] is v: print '\tthey are the same object'
else: print '\tthey are different'
print 'd.iteritems():'
for k,v in d.iteritems():
if d[k] is v: print '\tthey are the same object'
else: print '\tthey are different'
Run Code Online (Sandbox Code Playgroud)
输出:
d.items():
they are the same object
they are the same object
they are the same object
d.iteritems():
they are the same …Run Code Online (Sandbox Code Playgroud) 我创建了一个函数,它将在a中查找年龄Dictionary并显示匹配的名称:
dictionary = {'george' : 16, 'amber' : 19}
search_age = raw_input("Provide age")
for age in dictionary.values():
if age == search_age:
name = dictionary[age]
print name
Run Code Online (Sandbox Code Playgroud)
我知道如何比较和找到我只是不知道如何显示这个人的名字的年龄.另外,KeyError由于第5行,我得到了一个.我知道这不正确,但我无法弄清楚如何让它向后搜索.