从有条件的旧词典中得到新的词典?

时间:2009-12-03 08:43:59

标签: python dictionary

我是字典(字典词典)

    old_dict = {
    '1':{'A':1, 'check': 0, 'AA':2, 'AAA':3 , 'status':0},
    '2':{'A':11,'check': 0, 'AA':22, 'AAA':33 ,'status':1},
    '3':{'A':111,'check': 0, 'AA':222, 'AAA':333 ,'status':0},
    '4':{'A':1111,'check': 1, 'AA':2222, 'AAA':3333 ,'status':0},
    }

我想在['check']!= 0之前和['status']之前获得一本新词典!= 0 所以

    new_dict = {
    '1':{'A':1, 'check': 0, 'AA':2, 'AAA':3 , 'status':0},
    '3':{'A':111,'check': 0, 'AA':222, 'AAA':333 ,'status':0},
    }

如果是列表,我确实喜欢这个

    ouputdata = [d for d in data if d[1] == ' 0' and d[6]==' 0']

我试过了

for field in old_dict.values():
       if field['check'] !=0 and field['status'] != 0
          line = field['A'] + field['AA']+field['AAA']
         #write these line to file

如何使用字典。 你能帮我用字典做成吗

5 个答案:

答案 0 :(得分:5)

从yu_sha的答案中删除[]可以避免构建虚拟列表:

new_dict = dict( (k,v) for k,v in old_dict.iteritems() 
                         if v["status"] != 0 and v["check"] != 0 )

new_dict = dict(item for item in old_dict.iteritems() 
                         if item[1]["status"] != 0 and item[1]["check"] != 0)

答案 1 :(得分:5)

new_dict = {}
for k, d in old_dict.iteritems():
    if d['check'] == 0 and d['status'] == 0:
        new_dict[k] = d

答案 2 :(得分:3)

dict([x for x in old_dict.iteritems() if x[1]['status']==0 and x[1]['check']==0])

old_dict.iteritems()返回一对对列表。然后你过滤并转换回字典。

答案 3 :(得分:1)

outputdata = dict([d for d in data.iteritems() if d[1][1] == ' 0' and d[1][6]==' 0'])

答案 4 :(得分:0)

不是很有趣,不知道我为什么回答它。

In [17]: dict([(k, v) for k, v in old_dict.items() if v['check'] == 0 and v['status'] == 0])