相关疑难解决方法(0)

dict.items()和dict.iteritems()有什么区别?

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)

python dictionary python-2.x

673
推荐指数
6
解决办法
64万
查看次数

获取嵌套字典中所有键的列表

我想获取包含列表和字典的嵌套字典中所有键的列表。

我目前有这段代码,但似乎缺少向列表添加一些键,并且还重复添加了一些键。

keys_list = []
def get_keys(d_or_l, keys_list):
    if isinstance(d_or_l, dict):
        for k, v in iter(sorted(d_or_l.iteritems())):
            if isinstance(v, list):
                get_keys(v, keys_list)
            elif isinstance(v, dict):
                get_keys(v, keys_list)
            else:
                keys_list.append(k)
    elif isinstance(d_or_l, list):
        for i in d_or_l:
            if isinstance(i, list):
                get_keys(i, keys_list)
            elif isinstance(i, dict):
                get_keys(i, keys_list)
    else:
        print "** Skipping item of type: {}".format(type(d_or_l))
    return keys_list
Run Code Online (Sandbox Code Playgroud)

这仅需要一个空列表并用键填充它。d_or_l 是一个变量,并采用原始字典进行比较。

python dictionary nested

2
推荐指数
2
解决办法
1万
查看次数

标签 统计

dictionary ×2

python ×2

nested ×1

python-2.x ×1