简体   繁体   中英

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'

Here is the code as below:

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


for i,j in dict1.items():

    for k,l in j.items():

        if 'dict' in str(type(l)):

            l['value'] = l['Type']
            if '-' in l['Type']:
                l['operator'] = '='
            if ',' in l['Type']:
                l['operator'] = 'in'


print(dict1)

Try this

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

for v in d1.values():
    for y in v.values():
        if 'Type' in y.keys():
            y['value'] = y['Type']
            if '-' in y['Type']:
                y['operator'] = 'or'
            elif ',' in y['Type']:
                y['operator'] = '='
print(d1)

Output

{'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'}}}

For easy to read,

d1 = {
    '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'
        }
    }
}

For the sake of improving your coding skills, you might want to both use if statement rightfully, avoid multiple for statements (use recursive function instead). This will allow you to avoid corner cases causing issues.

Thus, you'll define a fonction to perform a recursive update of your dict object with the condition on the key 'Type' which must be available.

import re
def update_rule(rule: dict):
    if 'Type' in rule.keys():
        if ',' in rule['Type']:
            operator = '='
        else:
            operator = 'or'
        rule.update({'operator': operator})
    else:
        for v in rule.values():
            if isinstance(v, dict):
                update_rule(v)

Then, to get you updated dictionary, just apply the function to your input:

update_rule(my_input_dict)

With this code: you check if you have an inner dict with the 'Type' Key or not, like the "RULES" which contains "rule1", and you recursively call the function if it is the case. Your error came from the fact you did not ckecked if an inner rule was present or not. You have to handle both cases in the code.

With this code you obtain the exact expected output:

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


def addValue(d):
    if type(d) == type({}):
        for i,j in d.items():
            ##print("(i, j)", i, j)
            if type({}) == type(j):
                if "Type" in j.keys():
                    j['value']=j['Type']
                    if '-' in j['Type']:
                        j['operator'] = 'or'
                    if ',' in j['Type']:
                        j['operator'] = '='

            addValue(j)

addValue(dict1)
print(dict1)

Output is:

{'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'}}

or for easy reading:

{'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'}
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM