2

我需要最有效的方法来从字典中删除几个项目,现在,我正在使用下面给出的 stmt ......认为同样的事情应该在几行中完成。

for eachitem in dicta:
                del eachitem['NAME']
                del eachitem['STATE']
                del eachitem['COUNTRY']
                del eachitem['REGION']
                del eachitem['LNAME']

dicta = [{'name','Bob','STATE':'VA','COUNTRY':'US','REGION':'MIDWEST','LNAME':'Brian',Salary:6000}]

一旦删除,我只想要字典中的薪水项目。任何输入表示赞赏。

4

3 回答 3

6

如果您的示例数据是您正在处理的内容,而不是删除元素,只需使用该唯一键重新创建您的 dict

dicta = [{'Salary':e['Salary']} for e in dicta]

或者对我来说,创建一个列表而不是字典列表更有意义

dicta = [e['Salary'] for e in dicta]

但取决于您计划实现的目标

于 2013-02-21T18:12:21.533 回答
5

我想你可以使用:

for eachitem in dicta:
    for k in ['NAME','STATE','COUNTRY','REGION','LNAME']:
        del eachitem[k]

或者,如果您只想要 1 个密钥:

for eachitem in dicta:
    salary = eachitem['SALARY']
    eachitem.clear()
    eachitem['SALARY'] = salary

这可以完成我认为您想要的一切 - 否则,您可以通过以下方式完成它:

eachitem = {'SALARY':eachitem['SALARY']}
于 2013-02-21T18:06:13.693 回答
1

编辑:我说过听写理解是最快的:我错了。我不小心运行%timeit test3而不是%timeit test3(). 请参阅下面的结果。

def test1():
    dicta = [{'NAME':'Bob','STATE':'VA','COUNTRY':'US','REGION':'MIDWEST','LNAME':'Brian','Salary':6000}]
    remove = ['NAME','STATE','COUNTRY','REGION','LNAME']
    for d in dicta:
        for r in remove:
            d.pop(r)

def test2():
    dicta = [{'NAME':'Bob','STATE':'VA','COUNTRY':'US','REGION':'MIDWEST','LNAME':'Brian','Salary':6000}]
    remove = ['NAME','STATE','COUNTRY','REGION','LNAME']
    for d in dicta:
        for r in remove:
            del d[r]

def test3():
    dicta = [{'NAME':'Bob','STATE':'VA','COUNTRY':'US','REGION':'MIDWEST','LNAME':'Brian','Salary':6000}]
    remove = ['NAME','STATE','COUNTRY','REGION','LNAME']    
    dicta = [{k:v for k,v in d.iteritems() if k not in remove } for d in dicta]

# this is really what OP was looking for, the other 3 tests are more generalized.    
def test4():    
    dicta = [{'NAME':'Bob','STATE':'VA','COUNTRY':'US','REGION':'MIDWEST','LNAME':'Brian','Salary':6000}]
    remove = ['NAME','STATE','COUNTRY','REGION','LNAME']    
    dicta = [e['Salary'] for e in dicta]

%timeit test1()
# 100000 loops, best of 3: 2.32 us per loop    
%timeit test2()
# 1000000 loops, best of 3: 1.68 us per loop    
%timeit test3()
# 100000 loops, best of 3: 3.23 us per loop
%timeit test4()
# 1000000 loops, best of 3: 1.46 us per loop
于 2013-02-21T18:25:20.587 回答