开发者

Get new dict from old dict with condition?

开发者 https://www.devze.com 2022-12-13 15:24 出处:网络
I am an dictionary (Dictionary of dictionary) old_dict = { \'1\':{\'A\':1, \'check\': 0, \'AA\':2, \'AAA\':3 , \'status\':0}开发者_运维知识库,

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


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


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)


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.


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


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])
0

精彩评论

暂无评论...
验证码 换一张
取 消