简体   繁体   English

如何通过检查值将键添加到字典

[英]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'出现错误 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 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).为了提高您的编码技能,您可能希望同时使用 if 语句,避免使用多个 for 语句(改用递归 function)。 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.因此,您将定义一个函数来执行您的字典 object 的递归更新,条件是键“类型”必须可用。

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:然后,为了让您更新字典,只需将 function 应用于您的输入:

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.使用此代码:您检查是否有带有“类型”键的内部字典,例如包含“rule1”的“规则”,如果是这种情况,则递归调用 function。 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:使用此代码,您可以获得确切的预期 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: 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'}}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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