views:

163

answers:

5

I am an dictionary (Dictionary of 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},
    }

I Want to get a new dictionary that before['check'] != 0 and before['status'] != 0 so will be

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

If it's a list I did like this

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

I have tried

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

How Make it with dictionary. Could you help me to make it with dictionary

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

old_dict.iteritems() returns you a list of pairs. Which you then filter and convert back to dictionary.

yu_sha
+1  A: 
outputdata = dict([d for d in data.iteritems() if d[1][1] == ' 0' and d[1][6]==' 0'])
Amber
This returns "KeyError: 1" because elements of dictionary are actually dictionaries.
yu_sha
Um, no? `iteritems()` returns a list of 2-tuples.
Amber
Right. tuple[0] is the key, and tuple[1] is the value. And the value in the original post is the dictionary, like {'A':1, 'check': 0, 'AA':2, 'AAA':3 , 'status':0}
yu_sha
Ah, now I get you. Yeah.
Amber
Thanksssss all of you .:)
python
A: 

Not very interesting, don't know why I answer it.

In [17]: dict([(k, v) for k, v in old_dict.items() if v['check'] == 0 and v['status'] == 0])
ablmf
Not very interesting to you ,but your answer is very interesting to me.
python
+5  A: 

Dropping the [] from yu_sha's answer avoids constructing a dummy list:

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

or

new_dict = dict(item for item in old_dict.iteritems() 
                         if item[1]["status"] != 0 and item[1]["check"] != 0)
Anthony Towns
+4  A: 
new_dict = {}
for k, d in old_dict.iteritems():
    if d['check'] == 0 and d['status'] == 0:
        new_dict[k] = d
steveha