Sunday 13 December 2020

How to add key to dictionary by checking the value

  • I need to check 'Type' whether it '-' or ','

  • create a new key with 'value' which is same as 'Type'

  • if '-' then its 'or'

  • if ',' then its '='

The sample dictionary is below

{
    'RULES': {
        'rule1': {
            'Range': '0',
            'Type': '0-10'
        }
    },
    'rule2': {
        'Range': '1-10',
        'Type': '0,10',
    },
    'rule3': {
        'Range': '11-50',
        'order': '3'
    }
}

Expected out

{
   'RULES': {
       'rule1': {
           'Range': '0',
           'Type': '0-10',
           'value':'0-10',
           'operator' :'or'
       }
   },
   'rule2': {
       'Range': '1-10',
       'Type': '0,10',
       'value':'0,10',
       'operator':'='
   },
   'rule3': {
       'Range': '11-50',
       'order': '3'
   }
}

Code

for i,j in a.items():
    for k,l in j.items():
        l['value'] = l['Type']
        if '-' in l['Type']:
            l['operator'] = '='
        if ',' in l['Type']:
            l['operator'] = 'in'

Got error AttributeError: 'str' object has no attribute 'items'



from How to add key to dictionary by checking the value

No comments:

Post a Comment