将项目附加到python中的字典字典中时输出错误

时间:2018-11-09 06:49:48

标签: python dictionary

我在dictionary of dictionary中有一个空的python,我正在尝试向其中添加/添加项目。各个内部词典本身都有list作为其key值。

我的字典的空结构是:

grp_task_text_dict = {'Group 1': {}, 'Group 2': {}}

这是我当前的代码,该代码读取项目,并且根据某些条件,它需要将该项目附加到Group 1Group 2上:

def text_mapping_bot2():

    group_list = ['Group 1','Group 2']
    task_text_dict = {}
    grp_task_text_dict = {i: task_text_dict for i in group_list}
    grp_mapping = {i: [] for i in group_list}

    print('EMPTY GROUP TASK TEXT DICT = {}'.format(grp_task_text_dict))

    bot_mapping = [{'Name': '', 'Task ID': '0','Task Text': 'Try again!', 'Group': '', 'Complementary Action': ''}, {'Name': 'Hello', 'Task ID': '1.0','Task Text': 'Hi, Welcome', 'Group': 'Group 2', 'Complementary Action': 'group'}, {'Name': 'Hello', 'Task ID': '11.0', 'Task Text': 'Tell me about car options? ', 'Group': 'Group 2', 'Complementary Action': ''}, {'Bot Name': 'Hello', 'Task ID': '11.0', 'Task Text': 'What are different car options?', 'Group': 'Group 2', 'Complementary Action': ''}, {'Name': 'Hello', 'Task ID': '11.0','Task Text': 'What cars are there?', 'Group': 'Group 2','Complementary Action': ''}, {'Name': 'Hello', 'Task ID': '11.0','Task Text': 'May I know about Car types?', 'Group': 'Group 2','Complementary Action': ''}, {'Name': 'Hello', 'Task ID': '2.0', 'Task Text': 'How much is the rent of compact car? ', 'Group': 'Group 2','Complementary Action': ''}, {'Name': 'Hello', 'Task ID': '2.0','Task Text': 'Compact car expenses?', 'Group': 'Group 2', 'Complementary Action': ''}, {'Name': 'Hello', 'Task ID': '2.0', 'Task Text': 'Cost of compact car?', 'Group': 'Group 2', 'Complementary Action': ''}, {'Name': 'Hello', 'Task ID': '2.0','Task Text': 'How much do I need to pay for small car', 'Group': 'Group 2', 'Complementary Action': ''}]

    for item in bot_mapping:
        print("ITEM IN BOT MAPPING = {}".format(item))
        print('\n')
        print('\n')

        for grp, val in grp_task_text_dict.items():
            print('CURRENT VAL = {} and GROUP = {}'.format(val, grp))
            try:
                if last_id < int(float(item['Task ID'])):
                    last_id = int(float(item['Task ID']))
            except:
                pass
            try:
                if item['Task ID'] == '':
                    item['Task ID'] = '0'
                if (item['Task ID'] in val) and (str(item['Group']).lower() == str(grp).lower()):

                    print('\n')

                    print('CURRENT STATUS OF GROUP TASK TEXT DICT BEFORE APPENDING= {}'.format(
                        grp_task_text_dict))
                    print('\n')

                    print('GROUP AND TASK ID ALREADY IN ITEM AND TASK TEXT DICT IS SAME - {} and {}'.format(
                        str(item['Group']).lower(), str(grp).lower()))
                    print('\n')

                    print('APPENDING TO THIS GROUP IN GRP TASK DICT = {}'.format(grp_task_text_dict[grp][item['Task ID']]))

                    # val[item['Task ID']].append(item['Task Text'])
                    grp_task_text_dict[grp][item['Task ID']].append(item['Task Text'])
                    print('CURRENT STATUS OF GROUP TASK TEXT DICT AFTER APPENDING= {}. Going to Break out of loop'.format(
                        grp_task_text_dict))
                    break
                elif str(item['Group']).lower() == str(grp).lower():
                    print('CURRENT STATUS OF GROUP TASK TEXT DICT BEFORE APPENDING IN NEW TASK ID= {}'.format(
                        grp_task_text_dict))
                    print('\n')
                    print('NEW TASK ID BUT GROUP SAME = {} and {}'.format(str(item['Group']).lower(), str(grp).lower()))
                    print('\n')

                    print('APPENDING TO THIS GROUP IN GRP TASK DICT IN NEW ID = {}'.format(grp_task_text_dict[grp]))
                    print('\n')

                    # val[item['Task ID']] = [item['Task Text']]
                    grp_task_text_dict[grp][item['Task ID']] = [item['Task Text']]
                    print(
                        'CURRENT STATUS OF GROUP TASK TEXT DICT AFTER APPENDING IN NEW TASK ID = {}. Going to Break out of loop'.format(
                            grp_task_text_dict))
                    break
            except Exception as e:
                print("THIS EXCEPTION CAME = {}".format(e))
                # print('--iteration check--', task_text_dict)

我想要的是基于Group中每个item中提交的bot_mapping的代码,代码应该将其附加到与该组字典的Task ID关联的列表中如果该组字典中已经存在Task ID,则在grp_task_text_dict中,或者在Task ID的匹配组字典中使用新的grp_task_text_dict创建一个新列表。因此,例如,如果项目中的GroupGroup 2,而Task ID11.0,则应将此项目附加到{中的Task ID 11.0列表中Group 2的{​​1}}字典,不在grp_task_text_dict中。

当我执行此代码时,即使我的代码在匹配Group 1名称后使用Group 1附加到特定组,也将项目同时附加到Group 2grp_task_text_dict[grp][item['Task ID']].append(item['Task Text'])字典中使用Group

我的代码的示例输出如下:

if (item['Task ID'] in val) and (str(item['Group']).lower() == str(grp).lower()):

正如您在上面看到的,当它仅应附加到ITEM IN BOT MAPPING = {'Bot Name': 'Hello', 'Task ID': '11.0', 'Task Text': 'What are different car options?', 'Group': 'Group 2', 'Complementary Action': ''} CURRENT VAL = {'1.0': ['Hi, Welcome'], '11.0': ['Tell me about car options? ']} and GROUP = Group 1 CURRENT VAL = {'1.0': ['Hi, Welcome'], '11.0': ['Tell me about car options? ']} and GROUP = Group 2 CURRENT STATUS OF GROUP TASK TEXT DICT BEFORE APPENDING= {'Group 1': {'1.0': ['Hi, Welcome'], '11.0': ['Tell me about car options? ']}, 'Group 2': {'1.0': ['Hi, Welcome'], '11.0': ['Tell me about car options? ']}} GROUP AND TASK ID ALREADY IN ITEM AND TASK TEXT DICT IS SAME - group 2 and group 2 APPENDING TO THIS GROUP IN GRP TASK DICT = ['Tell me about car options? '] CURRENT STATUS OF GROUP TASK TEXT DICT AFTER APPENDING= {'Group 1': {'1.0': ['Hi, Welcome'], '11.0': ['Tell me about car options? ', 'What are different car options?']}, 'Group 2': {'1.0': ['Hi, Welcome'], '11.0': ['Tell me about car options? ', 'What are different car options?']}} 时,它同时附加到Group 1Group 2

我知道我的逻辑中有一些错误,但是我无法弄清楚导致此错误输出的原因和原因。有帮助吗?

1 个答案:

答案 0 :(得分:1)

问题是这一行:

grp_task_text_dict = {i: task_text_dict for i in group_list}

这将使该词典中的所有元素都引用同一task_text_dict词典,但不会获得副本。更改为:

grp_task_text_dict = {i: {} for i in group_list}

然后它将使用其自己的空字典初始化每个字典元素。