相关疑难解决方法(0)

867
推荐指数
8
解决办法
61万
查看次数

从python中不在列表中的对象中删除键?

我有这些钥匙:

keep = ["a","c"]
Run Code Online (Sandbox Code Playgroud)

我的词:

testdict = {'
'a':'vala',
'b':'valb',
'c':'valc',
'd':'vald'
}
Run Code Online (Sandbox Code Playgroud)

期望的输出:

testdict = {
'a':'vala',
'c':'valc'
}
Run Code Online (Sandbox Code Playgroud)

我想删除与列表中的键不匹配的所有键.最快的方法是什么?

我试过了:

for key, value in testdict.iteritems():
      if key not in keep:
         del testdict[key]
Run Code Online (Sandbox Code Playgroud)

但是由于尺寸变化,上面给出了错误.

python

9
推荐指数
2
解决办法
6495
查看次数

迭代和改变字典

我在迭代和修改字典时遇到问题......

假设我有一本字典:

dict1 = {'A' : 'first', 'B' : 'second', 'C' : 'third', 'D' : 'fourth'}
Run Code Online (Sandbox Code Playgroud)

我想迭代 dict1,使用其中的数据构建第二个字典。一旦完成了 中的每个条目dict1,我就会将其删除。

在伪代码中:

dict2 = {}

for an entry in dict1:
    if key is A or B:
        dict2[key] = dict1[key]   # copy the dictionary entry
    if key is C:
        do this...
    otherwise:
        do something else...
    del dict1[key]
Run Code Online (Sandbox Code Playgroud)

我知道改变循环中可迭代的长度会导致问题,并且上述内容可能不容易实现。

这个问题的答案似乎表明我可以使用该keys()函数,因为它返回一个动态对象。我因此尝试过:

for k in dict1.keys():
    if k == A or k == B:
        dict2[k] = dict1[k]
    elif k == C: …
Run Code Online (Sandbox Code Playgroud)

python dictionary

4
推荐指数
1
解决办法
1822
查看次数

标签 统计

python ×3

dictionary ×2